Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to solve the accuracy problem of C++ floating-point comparison

Shulou Source: shulou.com Published: 2022-05-31 14:30:58 10月05日 Update

This article mainly introduces "how to solve the accuracy problem of C++ floating point comparison". In daily operation, I believe many people have doubts about how to solve the accuracy problem of C++ floating point comparison. The editor consulted all kinds of data and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubt of "how to solve the accuracy problem of C++ floating point comparison". Next, please follow the editor to study!

1 introduction

Let me give you an example:

# include

Int main ()

{

Float a = 0.1

Float b = 0.2

Float c = a + b

If (c = = 0.3) {

Printf ("c = = 0.3\ n")

} else {

Printf ("0.1 + 0.2! = 0.3\ n")

}

Return 0

}

C! = 0.3

A _

If the variables a, b for 0.75, 0.5, you can see that the run c = = 1.25, which means that the floating-point operation is unstable.

A quarter of a century, a quarter of a century, a circle of 0.75, a circle of 1.25.

Why it can be good and bad, because not all decimals can be represented by the floating point standard (IEEE 754).

Therefore, judging whether two floating-point variables are equal cannot be simply achieved by the "= =" operator. When floating-point numbers are compared, the difference between them is generally within a certain range.

Bool feq (float a float b) {

Return fabs (afort b)

Tags: Binary decimal partial point integer valid precision problem real number number decimal point cantilever memory numeric value format symbol range storage learning right Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Docker Microsoft MariaDB Shulou Information Linux