简体   繁体   中英

The same arithmetic operations give different results in C++ and Python

I had to find the result of a function f(x) = x / (1-x)^2 , where 0 < x < 1 . The value had to be formatted up to 6 decimal places only.

Here is my C++ code:

float x; scanf("%f",&x);
printf("%.6f",x/((1-x)*(1-x)));

And I did for the same in Python:

 x = float(input()) 
 print ("%.6f" % (x/((1-x)**2)))

For some values of x, both the programs give different answers.

For example, for x = 0.84567 ,

C++ gives 35.505867 and Python gives 35.505874

Why does this happen?
According to solution, the Python answers are right, while C++ answers are wrong.

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <iomanip>

int main()
{
    const char data[] = "0.84567";
    float x; 
    sscanf(data, "%f",&x);

    double x2;
    sscanf(data, "%lf",&x2);

    std::cout << std::setprecision(8) << (x/((1-x)*(1-x))) << std::endl;
    std::cout << std::setprecision(8) << (x2/((1-x2)*(1-x2))) << std::endl;
}

sample output:

35.505867
35.505874

Conclusion:

Python is using doubles, you're using floats.

Python has implemented IEEE 754 double-precision, so its output is closer to real answer.

From documentation: https://docs.python.org/3/tutorial/floatingpoint.html#representation-error

Almost all machines today (November 2000) use IEEE-754 floating point arithmetic, and almost all platforms map Python floats to IEEE-754 “double precision”.

In C++ float is single-precision. Using double instead of float should give you similar output.

As others have pointed out, floating point numbers in python are implemented using double type in C. See section 5.4 of the Python Documentation.

Running this example on Coliru :

#include <cmath>
#include <cstdio>

int main()
{
    float pf = 0.84567f;
    printf("%.6f\n",pf/((1-pf)*(1-pf)));

    double pd = 0.84567;
    printf("%.6f\n",pd/((1-pd)*(1-pd)));

    return 0;
}

demonstrates the difference:

35.505867
35.505874

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM