Precise Python 2.7 calculation including Pi
<p>I am working on a small program that calculates different things related to orbital mechanics, such as the semi-major axis of an orbit, velocity etc. (No experience in this subject is required to answer this).</p>

<p>Everything worked out well, until I tried to calculate the orbital period (a formula where I had to use Pi):</p>

<p>T = 2Ï â a<sup>3</sup> / Âµ <a href="https://i.stack.imgur.com/cyS2I.png" rel="nofollow">(Click for image)</a></p>

<p>Where <em>T</em> is <em>time in seconds</em>, <em>a</em> is the <em>semi-major axis</em>, and <em>Âµ</em> is the <em>standard gravitational parameter</em>.</p>

<p>Now, my problem is that my program does not calculate it very precise, as the result of the formula is a bit off; for example: a circular orbit at an altitude of 160km should take approx 88 minutes, but my program tells me an approx of 90 minutes and 37 seconds.</p>

<p><strong>My code:</strong></p>

<pre><code>#the standard gravitational parameter of the Earth
gravPara = 3.986004418*10**14

#the semi-major axis of the orbit (the radius of the Earth + the apoapsis and periapsis of your orbit / 2)
semiMajor = (bodyDia + ap + pe) / 2

#formula to calculate orbital period
timeSeconds = (2 * math.pi) * math.sqrt(semiMajor**3 / gravPara)

#making the result appear as minutes and seconds instead of just seconds
timeMinutes = 0
while (timeSeconds &gt; 60):
   timeSeconds = timeSeconds - 60
   timeMinutes = timeMinutes + 1

#round the variable to store seconds
round(timeSeconds, 0)

#print the result
print timeMinutes
print timeSeconds
</code></pre>

<p>So my question is: is it an error in my code, or is <code>math.pi</code> not very precise when used together in such a formula? Should I store it as a float and use the float instead or should I split up the calculation into multiple pieces?</p>

<p>I would be very thankful if you could help me out on this one, as searching through the Python reference as well as other forums did not get me very far.</p>

<p>PS: when using <code>print math.pi</code> it returns a precise value of Pi, so the <code>math.pi</code> function seems to be working correctly.</p>

<p>Okay - seems like I have found the solution to my problem; while editing my question to include my calculation for the variable <em>semiMajor</em>, I realized I forgot to include parentheses around <code>bodyDia + ap + pe</code>, which caused faulty prioritizing, leading to the not-very-precise calculation.</p>

<p>So it was just a silly mistake in my code, and it was easily solved by adding two parentheses.
Thank you for taking your time.</p>

python python-2.7 math