November 5th, 2012, 07:11 PM
-
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)
November 5th, 2012, 09:35 PM
-
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: 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.
November 5th, 2012, 10:41 PM
-
November 6th, 2012, 09:55 AM
-
Questionable use of while: else:
Since your while loop hasn't got a break statement the code in the else: block always executes after the while condition fails. Your code would be less confusing without the else
Code:
while condition:
# statements
statement
It's likely, and understandable, that an earlier version of your program had a break statement and you didn't bother to change the else since it's valid.
[code]
Code tags[/code] are essential for python code and Makefiles!