Reputation: 3104
I am trying to calculate the 6th root of 2 in Swift and I cannot find a suitable function in for this.
There has been one post here titled "How to find the nth root of a value?" where the proposed solution was to use
pow(2, (1/6))
But I believe this does not work, as the signature for pow
is
func pow(_ x: Decimal, _ y: Int) -> Decimal
so the result of the above formula is 1 instead of 1.122462... as (1/6)
gets rounded to 0
.
The iPhone calculator can do it, so there must be way :)
Thanks!
Upvotes: 1
Views: 380
Reputation: 154613
To compute the 6th root of 2:
pow(2.0, 1.0/6.0)
You just need to use Double
s.
There are multiple versions of pow
for different data types. By using the floating point literals, Swift will infer them be of type Double
and select pow
with this signature:
func pow(_: Double, _: Double) -> Double
Or you can use logarithms (nth root of x is exp(log(x)/n)
where x
and n
are Double
s:
exp(log(2.0) / 6.0)
Upvotes: 5