Change language

Comparing floating point value in PHP

 
// Declare the value and initialize it $value1 = 8 - 6.4; $value2 = 1.6;  
// Compare values ​​ if ( $value1 = = $value2 ) { echo ’True’ ; } else { echo ’ False ’ ; }  
?>
Exit:
False
Explanation:Output of this code - False, which is very unpredictable, but in PHP, value1 is not exactly 1.6, that is, it comes from the difference between 8 and 6.4, which actually turned out to be 1.599999, so this statement turned out to be false. ,How to solve the above problem?

Method 1:
Use machine epsilon to test for equality in floating point values , or we can call it the smallest difference in computing in computer systems.Program 1:
// PHP float comparison program 
// Declare a variable and initialize
// this is a floating value $value1 = 1.23456789; $value2 = 1.23456780; $epsilon = 0.00001;  
// Use absolute difference and compare values ​​ if ( abs ( $value1 - $value2 ) < $epsilon ) { echo "True" ; } else { echo " False " ; }  
?>
Exit:
True
Explanation:This code uses two floating point numbers value1 and value2 along with epsilon ... Now take the absolute difference between the values ​​(value1 and value2) using a predefined function named abs(). This code will give an absolute value, but the question is why we are taking absolute values. You can see that both values ​​have the same digits after the decimal to the exact value 7. Which is very difficult for the system to parse the comparison.Method 2:we can use PHP round function .
// PHP float comparison program 
// Declare valid and initialize it $value1 = 8 - 6.4; $value2 = 1.6;  
// Use the rounding function to round // float to two decimal places
// and then compare that. var_dump ( round ( $value1 , 2) == round ( $value2 , 2));  
?>
Exit:
bool (true )

Shop

Best laptop for Sims 4

$

Best laptop for Zoom

$499

Best laptop for Minecraft

$590

Best laptop for engineering student

$

Best laptop for development

$

Best laptop for Cricut Maker

$

Best laptop for hacking

$890

Best laptop for Machine Learning

$950

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method