~starkingdoms/starkingdoms

ref: a032d20ee4fdccaa715bbde2cb73b318222ad6e1 starkingdoms/server/src/orbit/newtonian.rs -rw-r--r-- 790 bytes
a032d20e — c0repwn3r metrics 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
25
26
27
28
29
use crate::orbit::kepler::kepler_equation;

pub const NEWTONIAN_STEP_SIZE: f64 = 0.0001;
pub const NEWTONIAN_ACCEPTABLE_ERROR: f64 = 0.000_000_01;

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
}