Jump to content
xisto Community
Sign in to follow this  
Amezis

Php Is Doing Some Weird Calculations

Recommended Posts

Well, I am making a script that is doing lots of different calculations. Everything works, until I see something very strange:64 - 63.7035 = 0.29649999999999It's completely obvious that this is wrong. The answer should be 0.2965... Why does it do such a stupid error, and how can I fix it?

Share this post


Link to post
Share on other sites

After some testing, I discovered that with this code, it would work fine:

<?php$something = (64 - 63.7035);echo ("$something");?>

But my other code, which do the wrong calculation, is way longer. I don't know why... I've checked the variable, which should be 63.7035 and not 63.7035000000001, and it is correct.

By the way: It only happens with that number, I've tried with some other ones, but only the one I showed shows a wrong answer. I believe there's nothing to do with it...

Share this post


Link to post
Share on other sites

It's because of the way computers store numbers. They use binary, so sometimes you can't get a completely accurate number. The way that binary works in decimals is similar to the way it works in whole numbers:

463 = 256 + 128 + 64 + 8 + 4 + 2 + 1
Except for fractions and decimals, there are a lot of numbers that it is impossible to store exactly, because the denominator is not a power of 2. That's why with some calculations, you'll get the actual answer ? .000...001. It's easy to fix if you just round to several decimal places after you get the result, but unfortunately, there's no way to fix this at the source.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.