Do I have to worry about accuracy when using C ++ math functions with integers?

For example, the code below will give an undesirable result due to the precision of floating point numbers.

double a = 1 / 3.0;
int b = a * 3;      // b will be 0 here

I wonder if such problems will appear if I use mathematical functions. for instance

int a = sqrt(4);       // Do I have guarantee that I will always get 2 here?
int b = log2(8);       // Do I have guarantee that I will always get 3 here?

If not, how to solve this problem?

Edit:

Actually, I ran into this problem when programming an algorithm task. I want to get there

the largest integer that is a power of 2 and less than or equal to the integer N

So the round function cannot solve my problem. I know that I can solve this problem through a loop, but it seems not very elegant.

I want to know if

int a = pow(2, static_cast<int>(log2(N)));

. , N == 8, , log2 (N) - 2.9999999999999, 4 8?

+4
2

, , .

, log2(8) 3, ( *). log2.

:

double a = 1 / 3.0;
int b = a * 3;      // b will be 0 here

a 1/3, , a*3 1.0. , 1.0, . , a - 1/3, a 3 1.0, , IEEE 754: . , , .

sqrt log2

sqrt " ", sqrt(4) , , IEEE 754, 2.0.

log2 . IEEE 754 . . , log2, , , log2(8.0).

, log2, , 1 ULP . , , ( ). (, 3.0), .

, log2(8), : " log2, , 3.0`.

, . . , pow 1 ULP pow(10.0, 2.0) , , 99.0 100.0.

, int . ++ ( ). , , , . , 1/2:

int b = std::nearbyint(log2(8.0));

: , . , .

+8

, integer ++ , , .

:

  • , (, 3-1 × 10 -10= 2.9999999999 2)

  • , (, -3 + 1 × 10 -10= -2.9999999999 -2)

(1) (2) , int(x + 0.5) , .

round, , , , int(round(x)).

C99 ++ 11 lround(x).

, , , , 2.

, 1/65536 = 0.0000152587890625 , 0.1 , .

, 0,1 , , , 0,1 1.0 IEEE754.

, . , 10 0,1 1 , .

"", , , , , ( ).

, .

0

All Articles