Answer to Question #99660 in Python for Aryan

Question #99660
Hi, I had a homework to do which I don't quiet understand. It's this
Write a function approx_ln(x,n) that approximates the logarithm by n steps
of the above algorithm

with these information
It is based of computing the arithmetic and geometric mean of two values ai, gi
For a given value x > 0, initialize a_0 =(1+x)/2 , g_0 =√x,
• Iterate a_(i+1) =(a_i+g_i)2 and g_(i+1) =√ai+1gi
• Consider ( x−1)/a_i as an approximation to ln(x).

and after trying a lot I came up with this

def arithmetic_geometric_mean(a, g):
while True:
a= (a+g)/2
g=sqrt(a*g)
yield a, g

tol= 1e-5
def approx_ln(x, maxit=500):
a_0= (1+x)/2
g_0=sqrt(x)
for a,b in islice(arithmetic_geometric_mean(a_0, g_0), maxit):
if abs(a-b)<tol:
return (x-1)/a

which works but the question asks for different values of n and idk what to do
1
Expert's answer
2019-12-01T13:11:25-0500
from math import sqrt


def arithmetic_geometric_mean(a, g):
    while True:
        a= (a+g)/2
        g=sqrt(a*g)
        yield a, g



x = float(input("x="))
a_0 = (1+x)/2
g_0 = sqrt(x)



tol= 1e-5


def approx_ln(x, maxit=500):
    a_0= (1+x)/2
    g_0=sqrt(x)


    for i in range(maxit):
        for a,b in arithmetic_geometric_mean(a_0, g_0):
            if abs(a-b)<tol:
                return (x-1)/a

    return (x-1)/a


print(approx_ln(x,10000))

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS