JonahThePoo - 3 months ago 8x
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

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

``````E0 = M

``````

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)

}

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 {
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)
}
else{
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:

``````solveKeplersEquationForParamas(3.094763)
``````

Playground output:

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