Are all system floating point operations the same?

We make this web application in PHP, and when working in reports, we have Excel files to compare our results, to make sure that our encoding does the right thing.

Now we are faced with some differences due to floating point arithmetic. We do the same division and multiplication and go into slightly different numbers, which makes a significant difference.

My question is that Excel delegates its floating point arithmetic to the CPU, and PHP also relies on the CPU for its operations. Or does each application implement its own set of mathematical algorithms?

+4
source share
4 answers

Microsoft Excel uses its own double type on a specific machine to perform its calculations. I donโ€™t know exactly what PHP is using.

However, it should be noted that even copying a floating-point number on x86-based machines can change its value. Floating points are stored inside registers with a width of 80 bits. They are stored in memory in blocks of 64 bits wide. Therefore, assuming that Excel and PHP work on x86-based computers, you can get different values โ€‹โ€‹even with similar calculations. In particular, to the extremes of ranges supported by floating point types.

Finally, there is an obvious difference between double that Excel uses, and (if your PHP code uses one) float in PHP code. Make sure you are not incompatible with them, since float have much less precision.

EDIT: Forget about this too - there will be differences in output if PHP or Excel (rather, Excel) use / use the SSE extensions, since their floating point operations work on 64 bits, not 80 bits, double.

+3
source

Most systems implement IEEE 754 , which is not very healthy, but enough for most purposes. If you need higher accuracy, look at something like GMP .

+1
source

Be very careful when working with PHP float calculations. PHP is a flexible scripting language, but its flexibility and lack of typing can lead to dangers when casting or reading data.

I highly recommend you read the float pages in the PHP manual. There is a module called BC Math that is provided for arbitrary precision calculations, and depending on what you do, you may take advantage of it.

0
source

For greater but not arbitrary precision, try qd .

0
source

Source: https://habr.com/ru/post/1306870/


All Articles