-6

Simple Question:

When I do 1/2 in python shell it gives float value

>>> 1/2
>>> 0.5

But

sum = 0
for i in range(1, 20):
    p = 1/i
    print(p)
    val = 2.0**p
    sum += val
    print(sum)

When run this program, value of p always comes to 0.

What is the reason behind this behaviour. What am i missing?

sprksh
  • 1,698
  • 17
  • 33
  • [Python division](https://stackoverflow.com/q/2958684/2301450), [Division in Python 2.7. and 3.3 \[duplicate\]](https://stackoverflow.com/q/21316968/2301450) – vaultah Aug 21 '17 at 10:01
  • As that suggests, 1/2 in shell should also give 0. What is causing it to throw 0.5 in shell? – sprksh Aug 21 '17 at 10:04
  • 1
    It sounds like your script is probably being executed by Python 2. – Tom Zych Aug 21 '17 at 10:05
  • oh yes, you are right. Thanks for that. Already collected multiple downvotes. – sprksh Aug 21 '17 at 10:09

2 Answers2

1

That's probably because you are using python2.7

in python3 1/2 will return 0.5

to have the same results in python2.7 use this:

from __future__ import division
print(1/2) # output 0.5

Or as suggested by @Mahi use:

p = 1.0/i
Vikash Singh
  • 10,641
  • 7
  • 30
  • 59
0

Changing the 1 in 1/i to (1.0)/i will make it work

Like this:

sum = 0
for i in range(1, 20):
    p = (1.0)/i
    print(p)
    val = 2.0**p
    sum += val
    print(sum)

Or else, you could use p = 1/float(i) If the numerator or denominator is a float, then the result will be also.

This question is well discussed here.

HardCoder
  • 229
  • 2
  • 10