Get the App
SLTechnology News&Howtos  ›  Development  › 

How to solve the problem of precision loss of floating-point numbers in C language

Shulou Source: shulou.com Published: 2022-06-02 02:13:03 09月19日 Update

Editor to share with you how to solve the problem of precision loss of floating-point numbers in C language, I believe most people do not know much about it, so share this article for your reference. I hope you will learn a lot after reading this article. Let's learn about it!

First, let's take a look at the code # includeint main () {double test=0.1; printf ("% .100lf", test); return 0;} run the result:

The result directly from the phenomenon: the loss of accuracy is caused by the truncation of data caused by too many bits in the process of computer binary conversion, this result can be too large or too small.

To explain: first of all, to know the basic method of converting binary to decimal (except binary remainder, multiplying five, etc.), it is best to look at the storage of floating-point numbers, 0.1 here is a typical example, the remainder of 0.1 times five is inexhaustible, then the length of the binary sequence converted into data will be beyond the range of double. So much data will be truncated.

How to solve the problem

If you're thinking about completely letting the screen show 0.1, then you're not alone. That's what I thought at first, but it's impossible. But this is of little practical significance to us, after all, the effective section is enough.

What I'm going to solve here are two specific problems.

(1) size comparison of floating point numbers # includeint main () {double test=0.1; if (test== (1-0.9)) {printf ("normal");} else {printf ("whattered numbers!");} return 0;}

This code will output "what!". Why has it been said above that 0.1 times is inexhaustible? here, 0.5 is OK, because 0.5D is 0.1B in binary. Don't you get tired of thinking about it every time?

Solution

Import the macro DBL _ EPSILON defined in the library function.

The following paragraph here is in English that he is the minimum value that leads to x, n stands for EPSILON Ipsilon, x is any value.

In other words, any value smaller than EPSILON, if you add it to a number, will not change its value.

So, the loss of precision caused by a value smaller than EPSILON is within our allowable range.

# include#include#includeint main () {double test = 0.1; if (fabs (test-(1-0.9)) < DBL_EPSILON) {printf ("normal");} else {printf ("whattered eggs!");} return 0;}

There are two points in the picture above

1 . The fabs (a) below is the absolute value of a.

Imagine a number axis where the absolute value of their subtraction is their distance.

2 . If (fabs (test- 1-0.9)

Tags: Precision points problem binary article scope or that is data result language minimum two code content is in absolute value this is faceted interpretation Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS OPPO Reno Xiaomi Linux Apple