Round with gender in Objective-C

I compute g with e and s, which are all doubles. After that, I want to disable all digits after the second and save the result in x, for example:

g = 2.123 => x = 2.12

g = 5.34995 => x = 5.34

etc. I use...

g = 0.5*e + 0.5*s;
x = floor(g*100)/100;

... and it works great in most cases. But sometimes I get strange results. For instance:

e = 3.0 s = 1.6 g = 2.30 but x = 2.29 !!!

So, I tried to track the error:

g = 0.5*e + 0.5*s;
NSLog(@"%f",g);

gives g = 2.30

g = g * 100;
NSLog(@"%f",g);

gives me g = 230.0

x = floor(g);
NSLog(@"%f",x);

leads to x = 229.0 !!!

I do not understand! Please help me!: -)

+3
source share
3 answers

This will be related to floating point calculations.

Your calculation

g * 100

already returns

+229.99999999999997

.

INFO:

, , , . .

+3

, . , "/" . , / , , .

:

#define ACC 1e-7

double floorAcc( double x ) { return floor(x + ACC);}
double ceilAcc( double x ) { return ceil(x - ACC); }
double isLessThanAcc( double x, double y ) { return (x + ACC) < y; }
double isEqualAcc( double x, double y ) { return (x + ACC) > y && (x - ACC) < y; }

, . ACC.

+1

Here is a possible approach using intermediate integer results:

double e = 3.0;
double s = 1.6;

NSInteger e1 = e * .5 * 100.0; // 150
NSInteger s1 = s * .5 * 100.0; // 80

double x = (e1 + s1)/100.0; // 2.3
0
source

Source: https://habr.com/ru/post/1732651/


All Articles