Mathematica Asked by Asghar Bakerdar on May 19, 2021
I need to write a while or do loop to perform the iteration $x_{n+1}=Cos(x_n)$ with initial value $x_0=1$ and stops when the absolute value of the difference between two consecutive iterations is $|x_{n+1}-x_n|<epsilon$ , where $epsilon =10^{-16}$. Finally print the final value $x_{n+1}$, displaying 16 decimal digits.
I can define the relevant function and variables, but don’t know exactly how to execute the while loop to return me the required solution, here is my code:
epsilon = 10^{-6}
h[n] = Cos[n]
h[n + 1] = Cos[h[n]]
h[0] = 1
While[Abs[h[n + 1] - h[n]] < epsilon,
n = n + 1;
h[n + 1] = Cos[h[n]];
Print[h[n]]
]
I know other programming languages, but working with mathematica and its function layouts is a bit hard until I get used to it. If someone can help me how to set up this function with a while or do loop, and explain me its procedure, I will appreciate their effort and time.
You don't need to define any functions. You just need to write a While-loop.
It is tempting to write the While-loop to use system floating-point arithmetic for speed, like so:
With[{ϵ = 10.^-16},
Block[{x = 1., nxt},
While[True,
nxt = Cos[x];
If[Abs[nxt - x] < ϵ, Break[], x = nxt]];
nxt]]
But this doesn't work because system floating-point arithmetic can't maintain 16 digits of precision over the iteration. To avoid this numerics problem, the While-loop can be written to compute with exact numbers. The final value will be converted to a 16-digit arbitrary precision number.
With[{ϵ = 10^-16},
Block[{x = 1, nxt},
While[True,
nxt = Cos[x];
If[Abs[nxt - x] < ϵ, Break[], x = nxt]];
N[nxt, 16]]]
0.7390851332151606
The above can be simplified a little by using an undocumented feature of Break
. It returns its argument when given one.
With[{ϵ = 10^-16},
Block[{x = 1, nxt},
While[True,
nxt = Cos[x];
If[Abs[nxt - x] < ϵ, Break[N[nxt, 16]], x = nxt]]]]
The code editor complains about this use of Break
, but the evaluator accepts it and it works fine.
I also feel I should point out that it is better Mathematica practice to use FixedPoint
than to write a While-loop.
With[{ϵ = 10^-16},
N[FixedPoint[Cos, 1, SameTest -> (Abs[#1 - #2] < ϵ &)], 16]]
0.7390851332151606
Correct answer by m_goldberg on May 19, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP