🎓 A1Learner
🔍
0 of 47 lessons completed

Julia Numerical Methods

Numerical methods are step-by-step procedures that find an approximate answer to an equation a direct formula cannot solve easily. Each method repeats a fixed rule for a set number of steps.

Newton steps move a guess toward a root

The function repeats the Newton rule five times. The printout shows the rounded guess.

function newton_sqrt(x)
    for i in 1:5
        x = x - (x * x - 2.0) / (2.0 * x)
    end
    return x
end
println(round(newton_sqrt(1.0), digits=6))

Bisection halves an interval ten times

The function halves the interval ten times. The printout shows the rounded midpoint.

function bisect()
    lo = 1.0
    hi = 2.0
    for i in 1:10
        mid = (lo + hi) / 2.0
        if mid * mid < 2.0
            lo = mid
        else
            hi = mid
        end
    end
    return (lo + hi) / 2.0
end
println(round(bisect(), digits=6))

Newton steps work on a second equation

The function repeats the Newton rule five times for a new equation. The printout shows the rounded guess.

function newton_three(x)
    for i in 1:5
        x = x - (x * x - 3.0) / (2.0 * x)
    end
    return x
end
println(round(newton_three(1.0), digits=6))

Example

function newton_sqrt(x)
    for i in 1:5
        x = x - (x * x - 2.0) / (2.0 * x)
    end
    return x
end
function bisect()
    lo = 1.0
    hi = 2.0
    for i in 1:10
        mid = (lo + hi) / 2.0
        if mid * mid < 2.0
            lo = mid
        else
            hi = mid
        end
    end
    return (lo + hi) / 2.0
end
println(round(newton_sqrt(1.0), digits=6))
println(round(bisect(), digits=6))

Key points

  • Newton method: a method that improves a guess with the function value and its slope at that guess.
  • Fixed steps: a fixed count of steps gives the same result on every run.
  • Bisection: a method that halves an interval holding a root on each step.
  • Root: a value that makes the function equal zero.
  • Rounding: rounding to six digits keeps a printed answer short and easy to read.

In this example, the Newton function improves a guess five times. The bisection function halves an interval ten times. Both printouts show rounded answers.

Note

a fixed step count avoids a stopping rule that could differ between runs.

Try it Yourself

Edit the code, then press Run.

Running is simulated · JuliaHub

Exercise

What does bisection do on each step?