Usage of newton
¶
Suppose we want to solve \(e^x=x+c\) for multiple values of \(c\). We can create functions for \(f\) and \(f'\) in each case.
using FundamentalsNumericalComputation
for c = [2,4,7.5,11]
f = x -> exp(x) - x - c;
dfdx = x -> exp(x) - 1;
x = FNC.newton(f,dfdx,1.0); r = x[end];
println("root with c = $c is $r")
end
root with c = 2.0 is 1.1461932206205836
root with c = 4.0 is 1.7490313860127016
root with c = 7.5 is 2.2803781488230648
root with c = 11.0 is 2.610868638149876
There’s a subtlety about the definition of f
. It uses whatever value is assigned to c
at the moment f
is called. If we later change the value assigned to c
, the function is changed also.
c = 11; f = x -> exp(x) - x - c;
@show f(0);
f(0) = -10.0
c = 100;
@show f(0);
f(0) = -99.0