如何自己编写幂函数?
我一直想知道如何自己制作一个计算幂的函数(例如 23).在大多数语言中,这些都包含在标准库中,主要是作为 pow(double x, double y)
,但我如何自己编写?
I was always wondering how I can make a function which calculates the power (e.g. 23) myself. In most languages these are included in the standard library, mostly as pow(double x, double y)
, but how can I write it myself?
我在考虑 for 循环
,但它认为我的大脑陷入了循环(当我想用非整数指数计算幂时,例如 54.5 或底片 2-21) 然后我疯了 ;)
I was thinking about for loops
, but it think my brain got in a loop (when I wanted to do a power with a non-integer exponent, like 54.5 or negatives 2-21) and I went crazy ;)
那么,如何编写一个计算实数幂的函数?谢谢
So, how can I write a function which calculates the power of a real number? Thanks
哦,也许需要注意的是:我不能使用使用幂的函数(例如 exp
),这会使它最终变得毫无用处.
Oh, maybe important to note: I cannot use functions which use powers (e.g. exp
), which would make this ultimately useless.
推荐答案
负幂不是问题,它们只是正幂的倒数 (1/x
).
Negative powers are not a problem, they're just the inverse (1/x
) of the positive power.
浮点运算稍微复杂一点;如您所知,分数幂等效于根(例如 x^(1/2) == sqrt(x)
),并且您还知道以相同的基数乘幂等效于将它们的相加指数.
Floating point powers are just a little bit more complicated; as you know a fractional power is equivalent to a root (e.g. x^(1/2) == sqrt(x)
) and you also know that multiplying powers with the same base is equivalent to add their exponents.
有了以上所有内容,您可以:
With all the above, you can:
- 将指数分解为整数部分和有理部分一>.
- 使用循环计算整数幂(您可以优化它分解因子并重用部分计算).
- 使用您喜欢的任何算法计算根(任何迭代近似,如二分法或牛顿法都可以).
- 将结果相乘.
- 如果指数为负,则应用倒数.
示例:
2^(-3.5) = (2^3 * 2^(1/2)))^-1 = 1 / (2*2*2 * sqrt(2))
相关文章