Flourish PHP Unframework
This is an archived copy of the forum for reference purposes

Comparing within Delta

posted by ihumanable 9 years ago

I'm doing some calculations with floats and was wondering if there is any built in functionality to do a compare equality within delta.

More or less I'm doing this


$part_one = fRequest::get('part_one', 'float');  //This can be a float, like 32.5
$part_two = fRequest::get('part_two', 'float');  //This can be a float, like 67.5

$total = $part_one + $part_two;
$delta = 0.05;

//The total must be 100%
if( (100 - $delta) < $total && $total < (100 + $delta) ) {
  //Valid value
} else {
  //Throw an exception
}

Does fNumber support anything like this? Is this necessary in PHP? I know it's normally frowned upon to write code like "if(32.5 + 67.5 == 100) {" because IEEE floating point representation isn't exact and it might add up to 99.999999999765746857999 or something crazy like that.

Thanks for any help.

There isn't anything in fNumber to do what you described, but I would probably just use fNumber::add(), fNumber::lt(), fNumber::gt(), etc if you are concerned about floating point rounding issues.

~Also, I think there is an error in your code sample.~ Scratch that, I was reading it wrong.

posted by wbond 9 years ago