0

Here is my project on a small scale. The purpose is to approximate pi. I know it isn't neat, but the algorithm is correct.

adds = 0
subtracts = 0
for x in range(0, 10):
    adds += 1/(1 + 4*x)
    subtracts += 1/(3 + 4*x)
    print(adds) #DEBUGGING
    print(subtracts) #DEBUGGING

pi = float(4*(adds + subtracts)
print(pi)

Seems like it should work, right? On python 3, the same exact code gives me an accurate answer. However, in 2.7.10, this happens in the shell:

===================== RESTART: C:/Python27/Scripts/pi.py 
=====================
1
0
1
0
1
0
1
0
1
0
1
0
1
0
1
0
1
0
1
0
4.0
>>> 

Can someone explain to me why this happens and how I can correct this? I have tried conventional methods like converting to strings, formatting, rounding, etc. but none of them work. It is like my variables are being saved as 1's and 0's despite their values constantly changing. Once again, the same code works fine on Python 3.

cs95
  • 379,657
  • 97
  • 704
  • 746

2 Answers2

2

On python2, division between integers results in integer division with the final answer truncated to a whole number.

>>> 1 / 2
0

On python3, this is not the case, because division automatically results in a float result unless you use the // integer division operator explicitly.

You'll want to have at least one of the operands of float type:

>>> 1. / 2
0.5

for x in range(0, 10):
    adds += 1. / (1 + 4 * x)
    subtracts += 1. / (3 + 4 * x)

Note the 1. is 1.0.

cs95
  • 379,657
  • 97
  • 704
  • 746
0

On Python 2.7, x / y is integer division, but you can use Python 3's real division using __future__ division :

from __future__ import division
adds = 0
subtracts = 0
for x in range(0, 10):
    adds += 1/(1 + 4*x)
    subtracts += 1/(3 + 4*x)
    print(adds) #DEBUGGING
    print(subtracts) #DEBUGGING

pi = float(4*(adds + subtracts))
print(pi)

Out :

1.0
0.333333333333
1.2
0.47619047619
1.31111111111
0.5670995671
1.38803418803
0.633766233766
1.44685771745
0.686397812714
1.49447676507
0.729876073583
1.53447676507
0.76691311062
1.56895952369
0.799171175136
1.59926255399
0.827742603708
1.62628958102
0.853383629349
9.91869284146
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
  • Be careful changing the mechanics of the syntax, you might not expect this behaviour in every place. – cs95 Sep 04 '17 at 21:30
  • People are more familiar with `/` as being real division, that's one of the reasons it was changed in later versions, and changing it wouldn't be bad as long as you know how to use it. – DjaouadNM Sep 04 '17 at 21:33