Php Floating Point Precision - Complex Equation = 1

I have the following equation

1 - ((.5 * 0.83333333333333) ^ 2 + (.5 * 0.83333333333333) ^ 2 + (.5 * (1 - 0.83333333333333)) ^ 2 + (.5 * (1 - 0.83333333333333)) ^ 2)

In Php5, this gives an answer of 1, not 0.63 (on two machines, OSx and Centos). Should I exclusively use bc math functions for Php to do equations like this?

0


source to share


3 answers


I think maybe you should use pow () instead of the xor (^) operator :)



+5


source


Not really an equation, but it's semantics. Also, I doubt if you mean xor, so I am assuming this is not what you want. Anyway, can you use rational arithmetic?

0.83333 can be converted to a fraction (assuming 3 is a repeated decimal):



 83.3333333 = 100x
  8.3333333 = 10x
 -----------------
         75 = 90x
     x = 75 / 90 = 0.83333...

      

This way you are only dealing with integers and as long as both do not overflow (you can reduce the GCD before and after operations), then you should be fine.

+1


source


<?php

$hugeDamnEquation = pow(1 - ((.5 * 0.83333333333333), 2) + pow((.5 * 0.83333333333333), 2) + pow((.5 * (1 - 0.83333333333333)), 2) + pow((.5 * (1 - 0.83333333333333)), 2));

echo $hugeDamnEquation;

?>

      

+1


source







All Articles