如何自己写一个电源功能? [英] How can I write a power function myself?

查看:168
本文介绍了如何自己写一个电源功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直想知道如何使用一个函数来计算权力(例如2 3 )。在大多数语言中,这些都包含在标准库中,主要是 pow(double x,double y),但是如何自己写?



我在考虑 for循环,但它认为我的大脑进入了一个循环(当我想用一个非整数指数,像5 4.5 或负面2 -21 ),我疯了;)



我写了一个函数来计算实数的幂?感谢






哦,可能要注意:我不能使用使用权力的函数(例如 exp

解决方案

负权力不是一个问题,只需要正的幂的倒数( 1 / x )。



浮点数只是一点点更复杂;因为你知道小数幂等于一个根(例如 x ^(1/2)== sqrt(x)),你也知道,



  • 分解整数部分和理性部分中的指数


  • 使用循环计算整数幂(您可以根据因素优化其分解并重复使用部分计算)。


  • 如果指数为负,则应用任何算法(任何迭代近似,如二分法或牛顿法)。



  • 示例:

       


    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?

    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


    Oh, maybe important to note: I cannot use functions which use powers (e.g. exp), which would make this ultimately useless.

    解决方案

    Negative powers are not a problem, they're just the inverse (1/x) of the positive power.

    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:

    • Decompose the exponent in a integer part and a rational part.
    • Calculate the integer power with a loop (you can optimise it decomposing in factors and reusing partial calculations).
    • Calculate the root with any algorithm you like (any iterative approximation like bisection or Newton method could work).
    • Multiply the result.
    • If the exponent was negative, apply the inverse.

    Example:

    2^(-3.5) = (2^3 * 2^(1/2)))^-1 = 1 / (2*2*2 * sqrt(2))
    

    这篇关于如何自己写一个电源功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆