search
HomeBackend DevelopmentPHP TutorialFloating point calculation problem in php_PHP tutorial

If you use PHP’s +-*/ to calculate floating point numbers, you may encounter some problems with incorrect calculation results. For example, echo intval(0.58*100); will print 57 instead of 58. This is actually It is a bug that the underlying binary of the computer cannot accurately represent floating point numbers. It is cross-language. I also encountered this problem when using Python. Therefore, basically most languages ​​​​provide class libraries or function libraries for precise calculations. For example, PHP has a BC high-precision function library. Below, PHP training teacher Dane will introduce the use of some commonly used BC high-precision functions.

Example

 代码如下  

Why is the output 57? Is it a PHP bug?

I believe that many students have had such questions, because there are many people asking me similar questions, not to mention that people often ask on bugs.php.net...

To understand this reason, first we need to know the representation of floating point numbers (IEEE 754):

Floating point numbers, taking 64-bit length (double precision) as an example, will be represented by 1 sign bit (E), 11 exponent bits (Q), and 52-bit mantissa (M) (a total of 64 bits).

Sign bit: The highest bit represents the sign of the data, 0 represents a positive number, and 1 represents a negative number.

Exponent bit: represents the data raised to the power of base 2, and the exponent is represented by an offset code

Mantissa: Indicates the significant digits after the decimal point of the data.

The key point here is the representation of decimals in binary. As for how decimals are represented in binary, you can search on Baidu. I won’t go into details here. The key thing we need to understand is that for binary representation, 0.58 is infinite. Long values ​​(numbers below omit the implicit 1)..

The binary representation of 0.58 (52 bits) is basically: 00101000111101011100001010001111010111000010100011110.57 The binary representation (52 bits) is basically: 001000111101011100001010001 111010111000010100011110 And the binary numbers of the two, if calculated only through these 52 bits, are: www.111cn. net

 0.58 -> 0.579999999999999960.57 -> 0.5699999999999999 As for the specific floating point multiplication of 0.58 * 100, we do not consider it in detail. Those who are interested can look at it (Floating point), we will look at it vaguely with mental arithmetic... 0.58 * 100 = 57.999999999

Then if you intval it, it will naturally be 57…

It can be seen that the key point of this problem is: "Your seemingly finite decimal is actually infinite in the binary representation of the computer"

So, don’t think this is a PHP bug anymore, this is what it is…

PHP floating point type has an inaccuracy in +-*%/

For example:

 1.

 $a = 0.1;

 $b = 0.7;

 var_dump(($a + $b) == 0.8);

The printed value is 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 finite 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 math functions or the gmp function

The code is as follows

 代码如下  

$a = 0.1;
$b = 0.7;
var_dump(bcadd($a,$b,2) == 0.8);

$a = 0.1;
$b = 0.7;
var_dump(bcadd($a,$b,2) == 0.8);

bcadd — Add two high-precision numbers

bccomp — Compares two high-precision numbers, returns -1, 0, 1

bcdiv — divide two high-precision numbers

bcmod — Find the remainder of a high-precision number

bcmul — Multiply two high-precision numbers

bcpow — Find the power of high-precision numbers

bcpowmod — Find high-precision numerical power and modulus, very commonly used in number theory

bcscale — Configure the default number of decimal points, which is equivalent to "scale="

in Linux bc

bcsqrt — Find the square root of a high-precision number

bcsub — Subtract two high-precision numbers

Organized some examples

PHP BC high-precision function library includes: addition, comparison, division, subtraction, remainder, multiplication, nth power, configure the default number of decimal points, and square. These functions are more useful when it comes to monetary calculations, such as e-commerce price calculations.

 代码如下  
/**
  * 两个高精度数比较
  * 
  * @access global
  * @param float $left
  * @param float $right
  * @param int $scale 精确到的小数点位数
  * 
  * @return int $left==$right 返回 0 | $left$right 返回 1
  */
var_dump(bccomp($left=4.45, $right=5.54, 2));
// -1
  
 /**
  * 两个高精度数相加
  * 
  * @access global
  * @param float $left
  * @param float $right
  * @param int $scale 精确到的小数点位数
  * 
  * @return string 
  */
var_dump(bcadd($left=1.0321456, $right=0.0243456, 2));
//1.04
 
  /**
  * 两个高精度数相减
  * 
  * @access global
  * @param float $left
  * @param float $right
  * @param int $scale 精确到的小数点位数
  * 
  * @return string 
  */
var_dump(bcsub($left=1.0321456, $right=3.0123456, 2));
//-1.98
  
 /**
  * 两个高精度数相除
  * 
  * @access global
  * @param float $left
  * @param float $right
  * @param int $scale 精确到的小数点位数
  * 
  * @return string 
  */
var_dump(bcdiv($left=6, $right=5, 2));
//1.20
 
 /**
  * 两个高精度数相乘
  * 
  * @access global
  * @param float $left
  * @param float $right
  * @param int $scale 精确到的小数点位数
  * 
  * @return string 
  */
var_dump(bcmul($left=3.1415926, $right=2.4569874566, 2));
//7.71
 
 /**
  * 设置bc函数的小数点位数
  * 
  * @access global
  * @param int $scale 精确到的小数点位数
  * 
  * @return void 
  */ 
bcscale(3);
var_dump(bcdiv('105', '6.55957')); 
// 16.007

Note: Regarding the number of digits set, the excess is discarded instead of rounded.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/730239.htmlTechArticleIf you use PHP’s +-*/ to calculate floating point numbers, you may encounter some problems with incorrect calculation results. , for example, echo intval(0.58*100); will print 57 instead of 58. This is actually the bottom of the computer...
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
PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)