1

I'm working on a 2D-physics engine, and I need a certain variable to be precise only to the hundredths. Are there any methods for basically shaving off all of that unneeded precision?

I have tried things like

"{0:.2f}".format(a)

but that obviously produces a string, not a number.

I'm moving an object based upon its speed, and I want it to(obviously) stop when its value is 0.0, but it keeps going because its speed is really something like 0.0000562351.

FrigidDev
  • 119

2 Answers2

2

It is typical to compare floats using a tolerance, rather than by equality. This both avoids some of the issues with floating point arithmetic on computers and allows you to specify an appropriate level of precision. In your case, if you only care about hundredths of a unit:

if abs(speed - limit) < 0.01:
    ...

For example:

>>> abs(0.0 - 0.0000562351) < 0.01
True
jonrsharpe
  • 1,323
1

Try using decimal module.

It allows to manipulate precision. With local context you should get enough flexibility.

Example taken from docs:

from decimal import localcontext

with localcontext() as ctx:
    ctx.prec = 42   # Perform a high precision calculation
    s = calculate_something()
s = +s  # Round the final result back to the default precision

with localcontext(BasicContext):      # temporarily use the BasicContext
    print Decimal(1) / Decimal(7)
    print Decimal(355) / Decimal(113)
Fuxi
  • 171
  • I think your answer is right, but let me suggest you enhance it by showing a snippet on how precision is controlled by the user using decimal. (I know it is right there in the documentation, but it would make the answer more self-contained) – logc Jun 24 '14 at 08:02
  • You're right @logc. Done :) – Fuxi Jun 24 '14 at 08:17