JonahThePoo JonahThePoo - 1 year ago 81
iOS Question

find a solution to Kepler's equation (iOS) (swift)

I am writing codes to find a solution (E) to Kepler's equation:

E - e*sin(E) = M

and all angles are expressed in radians,
M = 3.52821,
e = 0.016714

and theses are the steps:

  1. First guess, put E = Eo = M

  2. Find the value of O = E - e*sin(E) - M

  3. If |O| <= 0.000006, go to step 6
    If |O| > 0.000006, proceed with step 4

  4. Find delta_E = O/(1-e*sin(E))

  5. Take new value E1 = E - delta_E, go to step 2

  6. The present value of E is the solution, correct within 0.000006 of the true value

However, I don't know how to write codes (swift) of those steps, please help me.

Answer Source

First of all some corrections in your question which you apparently forgot to mention and I had to look for here.

E0 = M

E = E1 on next iteration if solution not found

Regarding technical terms, E here is called Eccentric Anomaly and M is called mean Anomaly. Where as eps is precision diameter. Also, E=e according to the shared article

Also in swift, we use camel case naming convention for variables and constants but here I have tried to use your names so that you could understand the code.

Now back to business, Following methods will do it for you using recursion:

func solveKeplersEquationForParamas(M:Double)->Void{

    let E:Double = M
    let eps:Double = 0.000006
    let AbsoluteValueOfO:Double = getAbsoluteValueOfO(E, M: M,eps: eps)
    print(NSString(format:"Answer is:%f", AbsoluteValueOfO))


func getAbsoluteValueOfO(E:Double,M:Double,eps:Double) -> Double {
    var SinOFE: Double = Double(sin(E))
    SinOFE = E*SinOFE
    var E1 = E;
    let O = E - SinOFE - M

    var AbsoluteValueOfO = fabs(O)
    if AbsoluteValueOfO > eps {
        print("Solution not found. go to step 4");
        let denom = 1-E*sin(E)
        let absDenom = fabs(denom)
        if absDenom>0{
            let deltaE = O/denom
            E1 = E-deltaE
            AbsoluteValueOfO = getAbsoluteValueOfO(E1, M: M, eps: eps)
            print("Denom became 0, Can't divide by zero Denom is:%f",denom);
            return AbsoluteValueOfO

    else if AbsoluteValueOfO < eps || AbsoluteValueOfO == eps{
        print("Solution found. Returning the value");
        print(NSString(format:"Value of E is:%f", E1))
    return AbsoluteValueOfO

Running this in playground like:


Playground output:

enter image description here

NOTE: This is the Swift solution to the steps you have mentioned. Responsibility for any error in steps lies on you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download