Julia Project: Numerical Solver
A numerical solver is a set of steps that moves a guess closer to a value that satisfies an equation. This lesson builds one with a fixed number of steps.
One Newton step improves the guess
The equation is x squared minus 2, and the start is 1.0. One step moves the guess to 1.5.
function step(x)
return x - (x * x - 2) / (2 * x)
end
println(round(step(1.0), digits=6))Four fixed steps reach the root
The same step runs four times inside a function. The rounded result is the square root of 2.
function newton(x, n)
for i in 1:n
x = x - (x * x - 2) / (2 * x)
end
return x
end
println(round(newton(1.0, 4), digits=6))A different start reaches the same root
Starting at 2.0 instead of 1.0 still ends at the same rounded value after four steps.
function newton(x, n)
for i in 1:n
x = x - (x * x - 2) / (2 * x)
end
return x
end
println(round(newton(2.0, 4), digits=6))Example
function newton(x, n)
for i in 1:n
x = x - (x * x - 2) / (2 * x)
end
return x
end
x = newton(1.0, 5)
println(round(x, digits=6))
println(round(x * x - 2, digits=6))Key points
- Solver: a numerical solver is a set of steps that moves a guess closer to a value that satisfies an equation.
- Newton step: a Newton step uses the function value and its slope to make a better guess.
- Fixed count: a fixed count of steps gives the same result on every run.
- Rounding: rounding to six digits keeps a solver result short and easy to check.
- Residual: a residual is the function value at the final guess, and a small residual shows the guess is close.
In this example, the newton function runs five fixed steps from 1.0. The rounded guess is printed first, then the rounded residual is printed, and 0.0 shows the guess satisfies the equation.
Note
a solver result is printed rounded, never as a raw float, so the output stays stable.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
One Newton step for x squared minus 2 starts at 1.0. What is the new guess?