+ 1

What is the algorithm to calculate decimal power of a number ? (Like 2^1.3082)

Need of algorithm

23rd Apr 2019, 3:07 AM
Laksheya
Laksheya - avatar
7 odpowiedzi
+ 5
I don't know for sure how `pow` does it, but you can do it with a taylor series expansion. f(x) = f(0) + x f'(0) / 1! + x² f''(0) / 2! + x³ f'''(0) / 3! + ... Now, letting f(x) = n^x: n^x = 1 + x log n / 1! + x² log² n / 2! + x³ log³ n / 3! + ... So you can calculate `let logn = Math.log(n)` and then sum up `(x**i) * (logn**i) / factorial(i)` - as many of them as you need to get an accurate result. Of course we still have exponents, but it's all whole numbers. We are also trading `pow` for `log`, but you can find a similar series for the logarithm function (the mercator series). Maybe we can even simplify the above, to get rid of all exponents. n^x = 1 + x log n / 1! + x² log² n / 2! + x³ log³ n / 3! + ... n^x = 1 + x log n * ( 1 + x log n / 2 * ( 1 + x log n / 3 * ( 1 + ... ) ) ) Which means in code: for(let i = some_value; i > 0; --i) result = 1 + result * x * logn / i; EDIT: I coded it up, it doesn't look too bad! https://code.sololearn.com/WsE1NAsJHFKJ/?ref=app
23rd Apr 2019, 8:04 AM
Schindlabua
Schindlabua - avatar
23rd Apr 2019, 3:14 AM
Calviղ
Calviղ - avatar
+ 3
Depends, For square root (x^0.5) I think it is based in testing. You start counting from 0 to ∞ with step of y, if n * n == x: return n elif n * n > x: n -= y, y *= 0.1 If n*n is greater than x, the step would be decreased. I have an old code about it: https://code.sololearn.com/cGLkePeW9INZ/?ref=app
23rd Apr 2019, 5:35 AM
Seb TheS
Seb TheS - avatar
+ 3
Thank you very much Schindlabua ☺️☺️☺️☺️ I was searching for this algorithm for more than 3 months but finally you helped me. I don't know how to say thanks to you but again thank you very much !!!!!!
23rd Apr 2019, 10:20 AM
Laksheya
Laksheya - avatar
+ 2
Sorry, i misunderstood your questions.
23rd Apr 2019, 4:21 AM
Calviղ
Calviղ - avatar
+ 1
But Calviղ I want the power to be a decimal value For example:- 2^0.00002449 pow() library can do this but I want to do that without using pow() library. How does the pow() library did it ??? 🤔🤔🤔
23rd Apr 2019, 3:23 AM
Laksheya
Laksheya - avatar
+ 1
Hah, no worries! You're welcome!
23rd Apr 2019, 2:36 PM
Schindlabua
Schindlabua - avatar