如何自己编写幂函数?

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))

这篇关于如何自己编写幂函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How do compilers treat variable length arrays(编译器如何处理变长数组)
Deduce template argument from std::function call signature(从 std::function 调用签名推导出模板参数)
check if member exists using enable_if(使用 enable_if 检查成员是否存在)
Standard Library Containers with additional optional template parameters?(具有附加可选模板参数的标准库容器?)
Uses of a C++ Arithmetic Promotion Header(C++ 算术提升标头的使用)
Parameter pack must be at the end of the parameter list... When and why?(参数包必须位于参数列表的末尾...何时以及为什么?)