floating point arithmetic

F

fred8865

Hi all,

I understand that due to different arithmetic used in floating points
they are just approximations. Hence, 180/100=1 in my python interpreter.
How can I tackle this problem of inaccurate floating point numbers?
thank you

regards
xtd
 
M

Mensanator

Hi all,

I understand that due to different arithmetic used in floating points
they are just approximations. Hence, 180/100=1 in my python interpreter.
How can I tackle this problem of inaccurate floating point numbers?

Try actually using floating point numbers, not integers:
 
J

John Machin

I understand that due to different arithmetic used in floating points
they are just approximations. Hence, 180/100=1 in my python interpreter.

It's not "hence". What you are seeing is truncating integer division.
How can I tackle this problem of inaccurate floating point numbers?
1.8
 
R

Rob Clewley

I understand that due to different arithmetic used in floating points
they are just approximations. Hence, 180/100=1 in my python interpreter.

No, that's not the reason you get 1, it's because the current version
of python does integer division by default. Try doing 180.0/100 or
including

from __future__ import division

at the top of your scripts before dividing your numbers.
How can I tackle this problem of inaccurate floating point numbers?

There are few occasions for "regular" users to worry about the
inaccuracy of floating point, unless you are doing very technical
calculations at high precision. If you need decimals to be represented
"perfectly" in python (e.g. you are writing scripts for financial
applications), try importing the decimal package (look it up in the
python docs).

-Rob
 
G

Gabriel Genellina

I understand that due to different arithmetic used in floating points
they are just approximations. Hence, 180/100=1 in my python interpreter.
How can I tackle this problem of inaccurate floating point numbers?
thank you

In the current Python versions (2.2 and up), 180/100 means integer
division (because both operands are integer).
If you want a floating point result, use 180.0/100 or
float(some_variable)/100

Starting with Python 3.0, the / operator will return a floating point
result ("true division"). So in that Python version, 180/100 gives 1.8
To enable that behavior on Python 2.x, execute "from __future__ import
division":
1.8

In any Python version, 180//100 always means integer division:
1
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,228
Members
46,818
Latest member
SapanaCarpetStudio

Latest Threads

Top