Reputation: 191
I was playing around with a simple recursive formula and noticed that the code
p = 2.0
while p < 3.0:
print p
p = (6+p)**(0.5)
will print
*snip*
...
2.99999999952
2.99999999992
2.99999999999
3.0
3.0
3.0
3.0
3.0
3.0
Of course there will be some kind of approximation between 2.99999999999 and 3.0 (and before that) but what is actually happening here? For me it seems odd that the floating point 3.0 will be interpreted as something not quite 3.0 but still close enough to be called 3.0, several times in a row.
Am I doing something wrong, code-wise, here or is my interpretation correct? I if so, why is this happening?
Upvotes: 2
Views: 88
Reputation: 500893
If you change the print statement like so:
print '%.20f' % p
all will become clear:
2.00000000000000000000
2.82842712474619029095
2.97126692250060076006
2.99520732546189538681
2.99920111454065274614
2.99986684946859805123
2.99997780816268644344
2.99999630135816763854
2.99999938355963147174
2.99999989725993687628
2.99999998287665592400
2.99999999714610909862
2.99999999952435159045
2.99999999992072519106
2.99999999998678745783
2.99999999999779776161
2.99999999999963273822
2.99999999999993871569
2.99999999999998978595
2.99999999999999822364
2.99999999999999955591
Upvotes: 5
Reputation: 363817
This is due to the way print
formats your float. Try printing with
print("%.40f" % p)
Upvotes: 3