RedRose23 RedRose23 - 1 month ago 6
Python Question

Simple function with for loop

I'm stuck in a very stupid point while reading Numeric Analysis.

So I have the following program in python. And I can't figure why I get these results.

Where do I use the

i
in
heron(x,y)
to get these results?

Because only the first one makes sense for me. Why are the numbers decreasing if the i isn't used at all at the function?

def heron(x,y):
x=(x+y/x)*0.5
return x

x=1
y=2
for i in range(5):
x=heron(x,y)
print('Approximation of square root : %.16f'%x)


And the results:

Approximation of square root :1.5000000000000000
Approximation of square root :1.4166666666666665
Approximation of square root :1.4142156862745097
Approximation of square root :1.4142135623746899
Approximation of square root :1.4142135623730949


Edit: The code was given by my professor in class and I guess the only use of it was to explain few basic things of Python?

Answer

The line

for i in range(5):

only means:

Do the following five times.

The actual work is done in

x = heron(x,y)

which uses x as part of the arguments of heron and assigns the changed value back to it. So while y stays unchanged, x is changed with each call to heron. The changed x is then used as an argument to the next call.

Edit: I can't decide if this is a correct implementation because I don't know what algorithm you are trying to implement. But you only asked:

Why are the numbers decreasing if the i isn't used at all at the function?

Comments