About 10 ** -n and 0.1 ** n

Normally, in mathematics, we know that 10 powered by -n equals to 0.1 powered by n.
However, in python, this equation can not stand well.

Recently, I’m working on a project, that needs the calculation of gravity between two planets. As it’s known to all, the gravitational constant G = 6.67 * 10 ^ -11. According to the formula, I write a line of code which is grav_cons = 6.67 * 0.1 ** 11. However, when I executed my code, the answer went wrong. The value of gravity in several digits after the decimal point weren’t correct.
After that, I spent serveral hours checking my code, and finally found the mistake.
In python, the answer of a calculation that contains float value will always be a float value. However, in the piece of code, the computer just automatically convert the decimal values into binaries and do the calculations. After that, the computer convert the answer in binary into the answer in decimal system and return the value, which leads to a calculation errors and effect the answer. In the end, I change the code into 10**-11, and the program finally went correct.

Leave a comment