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.
x=1;While[Abs[Cos[x]-x]>=epsilon,x=Cos[x]];N[x,16]
and see if it does what you want. Perhaps include aPrint[N[Abs[Cos[x]-x],16]]
inside the the loop so you can watch the convergence until you believe you can trust it. $\endgroup$FixedPoint
? $\endgroup$h[n] = Cos[n]
isn't what you want; you only wanth[0] = 1
andh[n + 1] = Cos[h[n]]
. Otherwise, when given, say,h[3]
, should mathematica produceCos[3]
(first definition) orCos[h[2]]
(second)? However, the thing is that you don't actually want to use any of these definitions at all! The code inside the while loop is what's setting the value ofh[something]
; it shouldn't be set outside of that context if you're not going to use it, as it might produce weird behavior. $\endgroup$h[5] = Cos[h[4]]
stores the value of h[5] as part of its definition for h, while still remembering the prior values. But if you only need the last two values, you can just make a name for the most recent two values, e.g.h
andh0
, and have the "time of the while loop" implicitly provide your $n$. You can assign them both at once via{h,h0} = {Cos[h],h}
. (Note how the value ofh0
is thrown away, as it becomes "too old" to be relevant.) You could also eschew the second variable in favor of just the function applied toh0
, as suggested in another comment. $\endgroup$While
loop is reversed: as is, it's saying "while the difference is less than epsilon, execute my code". But you want "until the difference is less than epsilon"! I.e.,Abs[h-h0] >= epsilon
. Also: you currently haveepsilon = 10^{-6}
. Mathematica generally doesn't accept LaTeX notation; this is saying "10 to the power of the list containing the element -6". You want epsilon =10^(-6)
! $\endgroup$