0

I am to compute a sum (x_i = 1 / i**2) with a specific number of iterations, but Python rounds every float down to 0. Ex. in this code:

number_of_iterations = int(input("Write number of iterations: "))
x = 0.0
for i in range(1, number_of_iterations + 1):
    x += 1/(i**2)

print(x)

With number_of_iterations = 6, it prints out 1. I'm assuming the first iteration goes well, with x = 1, but the rest get the value 0.

1 Answers1

0

As you have figured out, your current code uses integer division. One way to change it to use floating-point division is by making the numerator into a floating-point number:

x += 1.0 / (i**2)

At this point it might be worth pointing out that this behaviour has changed in Python 3, where / always denotes floating-point division: https://www.python.org/dev/peps/pep-0238/

NPE
  • 486,780
  • 108
  • 951
  • 1,012