Dwen
Dwen

Reputation: 1

Precision problem with multiplying float values C++

#include <iostream>
#include <iomanip>


using namespace std;


int main()
{
    setlocale(LC_ALL, "RU");
    float P_a2, P_b2,result2,x,y,z;

    cout << "P_a(x)= 9,09*x^9– 9,09*x^3+ 9,09*x\n";
    cout << "P_b(x)= – 8980,032*x^6– 186,34*x^4– 649,23*x^2\n\n";

    x = 1.2;

    cout << "\n";

    y = x * x * x * x * x * x;

    P_a2 = ((9.09 * y - 9.09) * x * x + 9.09) * x;

    cout << setprecision(9) << P_a2 << "\n\n";


    z = x * x;

    P_b2 = ((-8980.032 * z - 186.34) * z - 649.23) * z;
    
    cout << setprecision(9) << P_b2 << "\n\n";
    result2 = P_a2 * P_b2;
    cout <<fixed<< setprecision(15) << result2 << "\n\n"; //prints -1184587.00000000

   
    //right answer is -1 184 586,9806370984
    
}

Is this problem related with type of the value? I really cant understand why it happens and what should i do... Can somebody please explain why does it happens with result2 and can i avoid it without changing the type?

P.S my bad, i've forgot to add the minus, right answer ofc is -1 184 586,9806370984

P.P.S yes, i know that this code can be optimized, but our teacher said us to do so. And yes parentheses are correct.

I know i can fix it by using double, i'm just asking if i can solve this problem without using it

Upvotes: 0

Views: 966

Answers (1)

Chen
Chen

Reputation: 330

There are two issues (not c++ issues, more of general floating point numerical calculation issues):

  1. float type is usually 6-7 decimal digits precision, using double would give you 15-16 decimal digits, more helpful for the problem. Seems like you need more digits than float to at least hold the result.

  2. There is a subtraction in P_a, so should watch for catastrophic cancellation when grouping the terms.

Upvotes: 1

Related Questions