Universal gravitation in C++
2012-07-15 Updated 2026-09-02 · faaa486With all the cool science thats been going around I decided that it would be fun to take some of the things I remember from High School physics and turn it into code. I decided to write a class that calculates the force between two objects using Universal Gravitation:
We start by creating a body with the properties of an object in space, I used x,y,z coordinates because I intend on using 3d rendering some time in the future, also, I will use these coordinates to calculate the distance between the centers of the two objects later. We will also declare a constructor and a function to calculate the force between the current instance object and a passed object.
This is the end result, MassObject.h:
;
Now for the implementation, the constructor is pretty straight forward, so I don't feel the need to explain myself there. The part we are focused on is the calculation of the force between the two objects. For the calculation we require the distance between the objects, this can be obtained using the theorem of Pythagoras on the current object and the object passed to the gravitationalForce() function.
Usually we would use sqrt() to find the square root to get the hypotenuse. However if we take a look at the formula for universal gravitation we see that it requires the distance squared, it would be a waste of CPU time to calculate the square root of something only to square it again, so instead we will calculate for r squared, this will also let us avoid having to #include cmath.h.
MassObject.cpp:
const float G = 6.67300E-11;
float
So there is our MassObject class for calculating the force between two bodies, but we should test it to see if everything is working alright. The best way to do this, is to do the "Earth Test". We know that gravity on earth is roughly 9.8N, so if we did our calculation for an object with the weight of 1kg on the surface of the earth the result should be roughly 9.8. Keep in mind that the mass of the earth is roughly 5.9722e24Kg and its radius roughly 6378.1e3 m. Lets test this in our main function to see if the calculations work properly.
To keep things as compact as possible, I stuck both the earth and the 1Kg object into an array of MassObjects.
main.cpp:
int
I get the following output:
Force: 9.79654
And I think thats close enough to 9.8 to call it a success.
Originally posted on Blogspot