問題描述
我一直想知道如何自己制作一個計算冪的函數(例如 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))
這篇關于如何自己編寫冪函數?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!