-1

I'm working on Python 2.7. I created a simple program that takes the radius (r = 6) of a sphere and calculates its volume. I used parentheses to try to group higher precedences together. When I used this program:

> import math as m
> sphere = (4/3)*(m.pi)*(6**3)
> print(sphere)

I obtained an incorrect value of 678.58

When I used this program:

import math as m
sphere = (4)*(m.pi)*(6**3)/3
print(sphere)

Regardless of how the parentheses were grouped, as long as I put the denominator at the end of the equation, I obtained the correct value 904.77792.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
mza
  • 13
  • 2

3 Answers3

1

The problem is that result of

x = 4/3
print(x) # this will print 1

Because 4 is of an integer type and you divide it by another integer. Therefore Python(2.7) returns 1 instead of 1.3333333. If you want to get a decimal value you can do

import math as m
sphere = (4.0/3)*(m.pi)*(6**3)
print(sphere)

In the second case when number m.pi is floating, this is why you get a correct result as you dividing floating number by integer.

0

As the others said, this is a matter of integer vs. float division.

To make division work like in Python 3 (i.e. always float division, unless you specifically use //), just start your program with:

from __future__ import division

...which will change the behavior of / to what you expect.

But is there any specific reason why you're using Python 2.7? It's been deprecated and it is not supported anymore. Aim to use Python 3 for new projects.

Jan Pokorný
  • 1,418
  • 15
  • 22
0

In Pyhton 2.7, a division between two int produces a int result. You can solve this by typecasting one of the arguments in the divisions to be float using one of the following options:

  • Add a dot in one argument:
x = (4./3)  # 1.33333
  • Explicit typecast of one argument:
x = (float(4)/3)  # 1.33333

By the way, do you really need to use Python 2.x? If you are developing something new, I recomend you to migrate to Python 3.x, because Python 2 has been deprecated in 2020.

samlima
  • 188
  • 10