Home  >  Article  >  Backend Development  >  Solutions to inaccurate floating point operations under PHP

Solutions to inaccurate floating point operations under PHP

墨辰丷
墨辰丷Original
2018-05-31 10:07:301492browse

This article mainly introduces the solution to the inaccurate floating point operation under PHP. Interested friends can refer to it. I hope it will be helpful to everyone.

Are you doing one recently? The problem of addition and subtraction is that floating point operations are inaccurate. It seems that it is true that interpreted languages ​​have problems with floating point operations.

First look at a piece of code:

The printed value is actually boolean false

Why is this? The PHP manual has the following warning message for floating point numbers:

Warning

Floating point precision

Apparently simple decimal fractions like 0.1 or 0.7 cannot be converted to the internal binary format without losing a bit of precision. This can lead to confusing results: for example, floor((0.1 0.7)*10) will usually return 7 instead of the expected 8, because the internal representation of the result is something like 7.9999999999... .

This is related to the fact that it is impossible to express certain decimal fractions accurately with a limited number of digits. For example, 1/3 in decimal becomes 0.3333333. . .

So never believe that the floating point number result is accurate to the last digit, and never compare whether two floating point numbers are equal. If you really need higher precision, you should use arbitrary precision mathematical functions or gmp functions

Then the above calculation should be rewritten as

The above is the entire content of this article, I hope it will be helpful to everyone's learning.


Related recommendations:

PHP implements SQL statement formatting function

phpMethod to implement monomorphic design pattern

Method of TP5 Request request object in PHP

The above is the detailed content of Solutions to inaccurate floating point operations under PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn