serso / android-calculatorpp

Android Calculator
421 stars 201 forks source link

The result of odd root is bad for negative numbers #199

Closed ghost closed 5 years ago

GrantMoyer commented 5 years ago

This is correct behavior. 3/2 + 3√(3)/2 is the principal cube root of -9. A number had n distinct nth roots. The principal root is the root with the smallest argument. You can get the root you want by using the magnitude of the principal root. Specifically you can define √m(x, m) = sgn(x) × abs(√n(x, m))

This solution will only work when x is a real number, however.

Erhannis commented 5 years ago

Note, btw, that the calculator interprets "-1^2" as "-(1^2)". With odd roots, it doesn't matter, but fyi.

GrantMoyer commented 5 years ago

My mistake. 3/2 + i 3√(3)/2 is a cube root of -27, not -9. The fact that the prinicpal root is the one with the smallest argument (counter-clockwise angle from the positive real axis) is by convention, and is not universal.

In all likelihood, √n(x, n) is computed as e^(ln(x) * 1/n). Since complex natural logarithm is a multivalued function, ln(r e^(i θ)) = ln(r) + i (n 2 π + θ) where r is positive, -π < θ ≤ π, and n is an integer, the principal branch of ln(x) (n = 0) is used. This is equivalent to the choice of principal root described above.

In particular, -x = x e^(i π), so √n(-x, n) is computed as e^(ln(r) / n + i π / n) = √n(x) * (cos(π / n) + i sin(π / n))