I have this function and I want to save the result of a calculation and use it in another calculation. I am new to python and as you can see I declare new variables, but I can't do that for n times and I know I need to use a for loop but can't define how. Can you help me
def aprox_ln(x,n):
a=(1+x)/2
print('a0',a);
g=math.sqrt(x)
print('g0',g)
anew = (a+g)/2
gnew = math.sqrt(a*g)
aa = (anew * gnew)/2
bb= math.sqrt(anew*gnew)
.
.
.
# and so on for n times
print(aprox_ln(5,10))
EDIT: I want to use the result of the variables A and G to calculate A1 = (A + G) / 2 and G1 = math.sqrt (A * G), and then use the result of A1 and G1 to calculate A2 and G2 with the same formula and so on until An and Gn
To save variables along the way in a repeating manner you can use a list, or you can make a recursive function call.
Appending to lists: https://www.programiz.com/python-programming/methods/list/append
Recursive programming: https://www.programiz.com/python-programming/recursion
If you can be more specific in what you want your program to do, we can give you more specific code examples of how to do it.
Update: I've included some code for what I think you would like to do.
def aprox_ln(x, n)
a = 1
g = x
lst = []
for i in range(n):
a = (a+g)/2
g = math.sqrt(a*g)
lst.append((a, g))
return lst
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.