Plotting in Julia and roots of functions

Julia is a modern language for data science and machine learning which can be seen as an alternative to Python. It's easy to plot graphs in Julia. First import the necessary packages (the latter package is used for typesetting labels via LaTeX):

using Plots
using LaTeXStrings

Let's plot the following function in the interval [0, 1.5]:

function f(x::Float64)
    x^3
end

We first create an array of x values, then calculates the y values and finally plot the graph and save the result to 'plot.png'.

x = range(0, 1.5, length=100)
y = f.(x)
p = plot(x, y, title=L"f", label=L"x^3", linewidth=2, xlabel=L"x", ylabel=L"y")
savefig(p, "plot.png")

f(x)=x^3

Let's now find the cube root of 2. As can be seen from the graph, it's located near x=1.25. We can use the Newton-Raphson formula to find the root to six decimal places (we're looking for the root of x^3 - 2, the initial estimate is 1).

function newtonraphson(x::Float64)
    x - (x^3 - 2) / 3x^2
end

function findroot(x0::Float64)
    x = newtonraphson(x0)
    if abs(x - x0) <= 1e-7
        return x
    end
    findroot(x)
end

x = findroot(1.0)
println(x)
println(x^3)

The iteration formula (the newtonraphson function) takes an estimate (x) and improves it by subtracting f(x)/f'(x) from it (where f' is the derivative of f).

Now the findroot function iteratively calls the iteration formula until the desired accuracy is achieved.

The result is 1.2599210498948732 which can be verified by evaluating 1.2599210498948732^3.

Data ScienceMathsJulia
Avatar for Petr Homola

Written by Petr Homola

Studied physics & CS; PhD in NLP; interested in AI, HPC & PLT

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.