+ 4

How to make a power function for fractional powers in C++?

I know that C++ has cmath and math.h libraries which provide pow() function. However, I want to build my own power function which can operate with fractional powers. I mean I can write a loop to find 2^50 or something with integral powers, but I need a function that can do fractional powers like 5^0.3 as well. What approach do I use here? I think Taylor series could be the solution. So this is what I thought: a^b = e ^ b ln(a) We know that Taylor expansion of e^x is: e^x = 1 + x + x^2/2! + x^3/3! .... but there is no standard expansion for ln(x)... [There is an expansion for ln (1+x) but it only works if |x|<1 , which means I could only find powers of numbers < 1 with it] How do I solve this problem?

7th Feb 2022, 1:58 PM
Aditya Aparadh
Aditya Aparadh - avatar
7 odpowiedzi
+ 2
let a = e*a'. then: ln a = ln (e*a') = ln e + ln a' = 1 + ln a' by the logarithm rules. So you could use the expansion you described, you just need to divide by `e` a couple times until your number falls into the -1<a<1 range. The taylor expansion for a^b maps really nicely to a for loop btw, see if you can figure it out :P https://code.sololearn.com/WsE1NAsJHFKJ/?ref=app
8th Feb 2022, 1:49 AM
Schindlabua
Schindlabua - avatar
+ 3
ok. it's a good practice project. Updated my code. Read the comments inside the code for various explorations I made on what the program do. Tweak and experiment. I tried to translate Schindlabua 's javascript to c++. The results are different at about the 14th decimal place. Which one is more accurate? I don't know, perhaps someone could explain... It was a learning experience. 😁 Good topic. included link so you don't have to scroll back. https://code.sololearn.com/cRQQmm3ACZMC/?ref=app
9th Feb 2022, 2:04 AM
Bob_Li
Bob_Li - avatar
+ 1
@Scindlabua Thanks This is great. Got it
8th Feb 2022, 1:30 PM
Aditya Aparadh
Aditya Aparadh - avatar
+ 1
Bob_Li I mentioned it on the first line of my question right? I DO want to reinvent the wheel..
8th Feb 2022, 3:42 PM
Aditya Aparadh
Aditya Aparadh - avatar
0
There is a series expansion of a^x a^x = 1+x(lna)+(xlna)^2/2!+(xlna)^3/3!+(xlna)^4/4!+⋯ This is called Maclaurin Series. got the idea from this link https://www.emathzone.com/tutorials/calculus/maclaurin-series-of-ax.html
7th Feb 2022, 2:14 PM
saurabh
saurabh - avatar
0
ROOKIE I know that one. It uses ln a, which is the main problem we are trying to solve.
7th Feb 2022, 3:28 PM
Aditya Aparadh
Aditya Aparadh - avatar
0
you can do that with cmath, why reinvent the wheel? https://code.sololearn.com/cRQQmm3ACZMC/?ref=app
8th Feb 2022, 3:31 PM
Bob_Li
Bob_Li - avatar