TransWikia.com

Create variables in a for loop

Mathematica Asked by Toño Bobadilla on October 20, 2020

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?

3 Answers

What about defining this recursively?

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

Correct answer by infinitezero on October 20, 2020

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 *)

Answered by Bob Hanlon on October 20, 2020

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} *)

Answered by chuy on October 20, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP