Float Comparison For Python

Hey, yeah, its not panda3d specific at all, but I found that I ended up using this kind of comparison alot to clip my floats when doing manual movement/camera calculations. Anyway, hope someone finds it useful like I do.

Ex.: compare 1.0 to 1.2 but allow 1.0 to be greater or lesser than 1.2 by 0.2 and still be considered equal. In this case they are considered equal.

#
# Util.py
#
# Author: mss
#

#
# determines if a is near b by the amount of c
#
# useful for floats when you want to compare them.
# 

def near(a, b, c):
    d = a - b
    if abs(d) <= abs(c):
        return True
    else:
        return False

(If there is something like this already in python, let me know and I will just remove this post…)

A little modification.

def near( a, b, delta = sys.float_info.epsilon ):
  return abs( a - b ) <= delta 

Without the third parameter it checks for equality.

I like. :astonished:

EDIT: I think epsilon is a bit large. I would go with a value of 0.1 as default.

Epsilon is a tiny number. 0.1 is huge by comparison.

Print it in python.

Sorry but i could not resist:

import sys;
print sys.float_info.epsilon
2.22044604925e-16

so sorry to constantexpected but that was a fail (i guess you missed the e thing: e-16 means mantissa multipled with 10 to the power -16).

No it is okay! Sometimes, even tho I’m drug free, my brain works like I’ve got a pound of boomers in me.