c++ - Ensure float to be smaller than exact value -


i want calculate sum of following form in c++

float result = float(x1)/y1+float(x2)/y2+....+float(xn)/yn 

xi,yi integers. result approximation of actual value. crucial approximation smaller or equal actual value. can assume values finite , positive. tried using nextf(,0) in code snippet.

cout.precision( 15 ); float = 1.0f / 3.0f * 10; //3 1/3 float b = 2.0f / 3.0f * 10; //6 2/3 float af = nextafterf( , 0 ); float bf = nextafterf( b , 0 ); cout << << endl; cout << b << endl; cout << af << endl; cout << bf << endl; float sumf = 0.0f; ( int = 1; <= 3; i++ ) {     sumf = sumf + bf; } sumf = sumf + af; cout << sumf << endl; 

as 1 can see correct solution 3*6,666... +3.333.. = 23,3333... output get:

3.33333349227905 6.66666698455811 3.33333325386047 6.66666650772095 23.3333339691162 

even though summands smaller should represent, sum not. in case applying nextafterf sumf give me 23.3333320617676 smaller. work? possible rounding error gets big nextafterf still leaves me above correct value?

i know avoid implementing class fractions , calculating exactly. i'm curious whether possible achieve goal floats.

try changing float rounding mode fe_towardzero.

see code example here:

change floating point rounding mode


Comments

Popular posts from this blog

html - Firefox flex bug applied to buttons? -

html - Missing border-right in select on Firefox -

c# - two queries in same method -