How can I write a power function myself?(如何自己编写幂函数?)
问题描述
我一直想知道如何自己制作一个计算幂的函数(例如 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))
这篇关于如何自己编写幂函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何自己编写幂函数?
基础教程推荐
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 初始化列表*参数*评估顺序 2021-01-01
- CString 到 char* 2021-01-01
