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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With