# Create variables in a for loop

I am very new to mathematica, but it would be much easier for me to use For loops in order to create variables. My train of thought was simple, but apparantly does not work. Let's say I defined these variables

ex1 = 1 + 0.5
ex2 = ex1 + 0.5^2/2!
ex3 = ex2 + 0.5^3/3!
ex4 = ex3 + 0.5^4/4!
ex5 = ex4 + 0.5^5/5!
ex6 = ex5 + 0.5^6/6!


Next step in my numerical methods class was to get the absolute error, which means subtracting the real value from the experimental value I would get from "ex1", for example. What we are trying to approximate here is e^0.5, by the way.

So what I did first was:

ae1 = (e^0.5 - ex1)


And just repeated that step for all of them. I'd like to introduce these into a For loop, though, where I'm defining variables and using past variables in the loop. My train of thought was:

For[i = 1, i < 7, i++, Print[aei = (e^0.5 - exi)]]


This obviously doesn't work, but is it possible to do something like this?

• You can use Series[E^x, {x, 0, 5}] // Normal to get taylor series of that function. – wuyudi Aug 18 at 16:59

ex[0] = 1;
ex[n_] := ex[n] = ex[n - 1] + 0.5^n/n!;


The double assignment in the second line is very important. This causes all function calls to be evaluated only once. Once it has been initially evaluated, it will be saved in ex[n].

Table[{k, ex[k]}, {k, 1, 10}] // TableForm

1   1.5
2   1.625
3   1.64583
4   1.64844
5   1.6487
6   1.64872
7   1.64872
8   1.64872
9   1.64872
10  1.64872

• Very useful, thank you! – Toño Bobadilla Aug 18 at 18:06
• If you are content with this answer, you can click on the checkmark below the upvote-counter, to signal your question has been answered. This will give the user some extra reputation. – infinitezero Aug 18 at 18:07
Clear["Global*"]


Continuing on with the suggestion by infinitezero to use recursion, use RSolve to find the general expression.

ex[n_] = ex[n] /.
RSolve[{ex[0] == 1, ex[n] == ex[n - 1] + (1/2)^n/n!}, ex[n], n][[1]]

(* (Sqrt[E] Gamma[1 + n, 1/2])/Gamma[1 + n] *)


The first several values are

ex /@ Range[0, 10] *)

(* {1, 3/2, 13/8, 79/48, 211/128, 6331/3840, 75973/46080, 354541/215040, \
17017969/10321920, 306323443/185794560, 2042156287/1238630400}


Which are approximately,

% // N

(* {1., 1.5, 1.625, 1.64583, 1.64844, 1.6487, 1.64872, 1.64872, 1.64872, \
1.64872, 1.64872} *)

%[[-1]] // InputForm

(* 1.6487212706873657 *)


The limit of this sequence is

Limit[ex[n], n -> Infinity]

(* Sqrt[E] *)

% // N[%, 20] &

(* 1.6487212707001281468 *)


One more way, using FoldList:

FoldList[#1 + 0.5^#2/#2! &, 1 , Range[7]]
(* {1, 1.5, 1.625, 1.64583, 1.64844, 1.6487, 1.64872, 1.64872} *)
`