There are many built-in functions that contain AccuracyGoal
, PrecisionGoal
and WorkingPrecision
.
For instance
NSolve
NSolve[x^3 + 2 x + 7 == 0, x, WorkingPrecision -> 40]
{{x -> -1.568946403052382267352334751687751405502}, {x -> 0.784473201526191133676167375843875702751 - 1.961171744579820388573529019015063895809 I}, {x -> 0.784473201526191133676167375843875702751 + 1.961171744579820388573529019015063895809 I}}
FindRoot
FindRoot[Sin[x - 10] - x + 10, {x, 0}, AccuracyGoal -> 4, PrecisionGoal -> 4]
{x -> 9.99852}
FindRoot[Cos[x^2] - x, {x, 1}, WorkingPrecision -> 40]
{x -> 0.8010707652092183662168678540865655855422}
Here, I have a function Newton
that using Newton method to find a numerical root of a equation.
Options[Newton] = {MaxIterations :> $RecursionLimit};
Newton::noconv = "Iteration did not converge in `1` steps.";
Newton::usage = "Newton[func, x0] finds a zero of the function func
using the initial guess x0 to start the iteration. "
Newton[func_, x0_, opts : OptionsPattern[]] :=
Module[{res, maxIter, extraPre = 10},
maxIter = OptionValue[MaxIterations];
With[{prec = Precision[x0], fp = func'},
Block[{$MaxPrecision = prec + extraPre},
res = FixedPoint[(# - func[#]/fp[#]) &, x0, maxIter]
];
If[! TrueQ[Abs@func[res] < 10^-prec],
Message[Newton::noconv, maxIter]];
res
]
]
Newton[expr_, x_, x0_, opts : OptionsPattern[]] :=
Newton[Function[x, expr], x0, opts]
Newton Test
Newton[#^3 + 4 #^2 - 10 &, 1.2]
1.36523
Newton[x (x + 1), x, -1.2]
-1.
Question
How to add the options
AccuracyGoal
,PrecisionGoal
andWorkingPrecision
toNewton
. Namely,Options[Newton] = {MaxIterations :> $RecursionLimit, AccuracyGoal -> Automatic, PrecisionGoal -> Automatic, WorkingPrecision ->Automatic}
Is there a general strategy for implementing the options
AccuracyGoal
,PrecisionGoal
andWorkingPrecision
in a numerical function?
However, I have no idea to achieve this.
In addition,
Update
As Jens said
This could also be done for precision instead. But right now I don't know how to write a general answer that would be applicable for all cases.
So is it possible to know how WRI
implement these options(PrecisionGoal
and AccuracyGoal
,and WorkingPrecision
) in their built-ins?
Or how to add these options in my Newton
function?
FindRoot[Cos[x^2] - x, {x, 1.}, WorkingPrecision -> 40]
? In particular, what is the result ofPrecision[x /. First[%]]
? $\endgroup$FixedPoint
reminded me of what I did here. In that answer, I useSameTest
to stop when a desired accuracy is met. This could also be done for precision instead. But right now I don't know how to write a general answer that would be applicable for all cases. $\endgroup$