abhi
abhi

Reputation: 59

Floating point numbers do not work as expected

In the code below when i give input as 1 10 2 1 2 2, sum is printed as 52 and sum3 as 31.200001 whereas it shld have been 31.200000

int main(){

    int t,n,i,a[2000],m,j,f;
    scanf("%d",&t);
    while(t--){
        scanf("%d",&n);
        scanf("%d",&f);
        for(i=0;i<f;i++){
            scanf("%d",&a[i]);
        }
        scanf("%d",&m);
        if(n!=0){
            int sum=n*(n+1)/2;
            int sum2=0;
            for(j=0;j<i;j++){
                sum2+=a[j];
            }
            sum-=sum2;
            printf("%d\n",sum);
            float sum3;
            if(n%2==0) sum3=(1.0-2.0*m/n)*sum;
            else sum3=(1.0-2.0*m/(n+1))*sum;
            printf("%f\n",sum3);
        }
        else printf("0.0000\n");
    }
    return 0;
}

Upvotes: 1

Views: 298

Answers (6)

Rahul Bhojwani
Rahul Bhojwani

Reputation: 85

You can use printf("%g\n",sum3); instead of printf("%f\n",sum3); in your code to get proper output..

I hope it will work.

Upvotes: 0

Cubbi
Cubbi

Reputation: 47428

The decimal number 31.2 is not representable as a binary fraction. To be more specific, the nearest value of type float is 31.200000762939453125 which is exactly 8178893 * 2-18.

If you need a number that is closer to the decimal 31.2, consider using the type double, where your result would be 31.199999999999999289457264239899814128875732421875 or 8782019273372467 * 2-48

Upvotes: 2

Ed Heal
Ed Heal

Reputation: 59997

.. But you can try to reduce this possibility. You need to take into account of the exponents for addition/subtraction amongst other things.

Upvotes: 0

Michael Borgwardt
Michael Borgwardt

Reputation: 346290

From the Floating-Point Guide:

Why don’t my numbers, like 0.1 + 0.2 add up to a nice round 0.3, and instead I get a weird result like 0.30000000000000004?

Because internally, computers use a format (binary floating-point) that cannot accurately represent a number like 0.1, 0.2 or 0.3 at all.

When the code is compiled or interpreted, your “0.1” is already rounded to the nearest number in that format, which results in a small rounding error even before the calculation happens.

Upvotes: 5

Stephen Canon
Stephen Canon

Reputation: 106167

31.2 is not a representable number in binary floating-point. No matter what calculation is used to produce it, you will never get a float which is exactly equal to 31.2. The answer you got is about as good as you can reasonably expect.

Upvotes: 0

cheeken
cheeken

Reputation: 34655

This is the nature of floats. They are not guaranteed to be perfectly accurate.

See here for more detail on how/why this is the case.

Upvotes: 0

Related Questions