1. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Nov 2012
Posts
7
Rep Power
0

#### While loops

python novice.
Trying to link two functions with embedded while loops. Each function (base(i) and sqform(base) works on its own. But when linked I can't get it to work.

Attempting to get the following output:

ex: i = 4

4.0, 2.0, 2.0
3.0, 1.73, 1.73
2.0, 1.41, 1.41
1.0, 1.0, 1.0

currently only getting:

4.0, 2.0, 2.0

using version 2.7.3 writing gedit

Code:
```from math import *

def base(i):
base = i
while base > 0:
sqform(base)
base = base - 1

def sqform(base):
a = base
x = base - 1
y = (x + a/x)/2
while y != x:
x = y
y = (x + a/x)/2
else:
print float(a), float(x), float(sqrt(a))

i = int(raw_input('Enter number.\n'))
base(i)```
2. No Profile Picture
Contributing User
Devshed Intermediate (1500 - 1999 posts)

Join Date
Feb 2004
Location
San Francisco Bay
Posts
1,939
Rep Power
1313
Hint: what's the result of "3/2" in Python (before Python 3)? It isn't 1.5. You can avoid this either by making sure the arguments to sqform are always float or by putting the line
Code:
`from __future__ import division`
at the top of your code. (Or just switch to Python 3, but that will break other parts of your code.)

Another important thing: it's almost never a good idea to use exact equality of iterates as your convergence criterion in an iterative computation of floating-point values. In the case of your algorithm, there are cases where the iteration will enter an infinite loop. (If you start trying randomly generated inputs, you'll hit one eventually.) The usual way to decide when the iteration has "converged" is to see if the difference of two consecutive iterates is small enough. In other words, replace this:
Code:
`    while y != x:`
with this:
Code:
`    while abs(y-x) > tolerance:`
`tolerance' should be set to some small number of your choosing. For example, if tolerance=1e-14, then you'll get about 14 digits of accuracy, which is probably more than you'll need.
3. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Nov 2012
Posts
7
Rep Power
0
```while condition: