[Solved] Off-Topic PHP-Math

Status
Not open for further replies.

mudshark79

Member
While doing some improvements on one of my Fabrik-Applications and banging my head for maybe 5 hours I found out out a lot of interesting things about floating-point-Numbers in general but also that even the most simple math goes wrong from time to time?

It basically breaks down to this:
On some Ubuntu-Host of mine, PHP 5.5.9
echo var_dump((int)230918/(int)100);
gives
float(2309.18) test

On a shared hoster with PHP 5.4.39 this:
echo var_dump((int)230918/(int)100);
gives
float(2309.1799999999998363)

Now I understand that there may be no proper representation for certain floating-point numbers but 2309.18 isn't one of these, ain't it? But even more important, this only shows on one server and not on the other? Is there some switch in the config? Why are some those simple things so hard sometimes?

Comments appreciated :),

Regards,

Matthias
 
Last edited:
It's not just a PHP issue, it's inherent to floating point arithmetic on computers period, simply because there literally is no binary floating point representation for most fractions, and yes .18 is one of them. I won't try and explain why, as we'd be here all day.

Yes, there is an INI setting for precision, which you can set in your code ...

ini_set('precision', 8);

... but ... the effects may not be entirely what you expect. Although I suspect the different results you are seeing are due to different precisions in the main INI.

Long story short, there's various ways to work round it and achieve consistent (and correct) results across platforms and PHP versions, like using the bcmath module.

There's a good discussion about the issue here:

http://stackoverflow.com/questions/...precision-workaround-for-floating-point-issue

-- hugh
 
You are right, the precision value of the PHP.ini was not 8 but 20 (reason unclear, maybe i fiddled around with that once :rolleyes:) and now also the code I initially came up with for my overall really simple calculations starts working again. Also some error in some pdf-export disappeared.

So lesson learned and many thanks for your reply. I got myself educated on floating-point Numbers in general yesterday for the first time but the material I watched was not tailored for php but Javascript so I Still missed the part that I can adjust that behavior in PHP via that precision value. Phew..

Regards,

Matthias
 
I think 20 is the default. Be careful with changing the precision, though. It can have unforeseen side effects.

-- hugh
 
I double checked it on my ubuntu hosts and shared hosts, 14 seems to be the default value.

Thanks again for clearing this up!

Matthias
 
Status
Not open for further replies.
We are in need of some funding.
More details.

Thank you.

Staff online

Members online

Back
Top