~starkingdoms/starkingdoms

ref: 459e397588120fcd0a08caa09d1312ab1bf9b0b8 starkingdoms/server/src/orbit/newtonian.rs -rw-r--r-- 760 bytes
459e3975 — c0repwn3r infra overhaul 2 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
use crate::orbit::kepler::kepler_equation;

pub const NEWTONIAN_STEP_SIZE: f64 = 0.0001;
pub const NEWTONIAN_ACCEPTABLE_ERROR: f64 = 0.00000001;

pub fn solve_kepler_with_newtonian(mean_anomaly: f64, eccentricity: f64, max_iterations: u64) -> f64 {
    let mut guess = mean_anomaly;

    for _ in 0..max_iterations {
        let y = kepler_equation(guess, mean_anomaly, eccentricity);

        // exit early if output of function is very close to zero
        if y.abs() < NEWTONIAN_ACCEPTABLE_ERROR {
            break;
        }

        // otherwise, update guess
        let slope = (kepler_equation(guess + NEWTONIAN_STEP_SIZE, mean_anomaly, eccentricity) - y) / NEWTONIAN_STEP_SIZE;
        let step = y / slope;
        guess -= step;
    }

    guess
}