Skip to content

Instantly share code, notes, and snippets.

@mcsee
Created June 2, 2024 22:37
Show Gist options
  • Save mcsee/1bf7ef05cd9f36178204668f92ccafcf to your computer and use it in GitHub Desktop.
Save mcsee/1bf7ef05cd9f36178204668f92ccafcf to your computer and use it in GitHub Desktop.
// Define the gravitational constant
const G = 6.67430e-11; // m^3 kg^-1 s^-2
/**
* Calculate the gravitational force between two masses.
* @param {number} m1 - Mass of the first object in kilograms.
* @param {number} m2 - Mass of the second object in kilograms.
* @param {number} r - Distance between the centers of the masses in meters.
* @returns {number} - Gravitational force in Newtons.
*/
function calculateGravitationalForce(m1, m2, r) {
// Ensure the distance is not zero to avoid division by zero
if (r === 0) {
throw new Error("Distance between masses cannot be zero.");
}
// Calculate the gravitational force
const force = G * (m1 * m2) / (r * r);
return force;
}
// Example usage:
const mass1 = 5.972e24; // Earth's mass in kg
const mass2 = 7.348e22; // Moon's mass in kg
const distance = 3.844e8; // Distance between Earth and Moon in meters
const gravitationalForce = calculateGravitationalForce(mass1, mass2, distance);
console.log(`The gravitational force between Earth and Moon is ${gravitationalForce} N.`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment