如何计算浮点数的Python浮点数的根 [英] How to calculate Python float-number-th root of float number

查看:224
本文介绍了如何计算浮点数的Python浮点数的根的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Stackoverflow上找到了以下答案:

https://stackoverflow.com/a/356187/1829329

但它仅适用于在第n个根中为n的整数:

import gmpy2 as gmpy

result = gmpy.root((1/0.213), 31.5).real
print('result:', result)

导致:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-14-eb4628226deb> in <module>()
      8 
----> 9 result = gmpy.root((1/0.213), 31.5).real
     10 
     11 print('result:', result)

TypeError: root() requires 'mpfr','int' arguments

什么是计算此类根的好而精确的方法? (这是某些公式的python代码表示形式,我需要在课堂上进行计算.)

EDIT#1

这是我根据Spektre的回答和通过此处http://://math.stackexchange.com .

import numpy as np

def naive_root(nth, a, datatype=np.float128):
    """This function can only calculate the nth root, if the operand a is positive."""
    logarithm = np.log2(a, dtype=datatype)
    exponent = np.multiply(np.divide(1, nth, dtype=datatype), logarithm, dtype=datatype)
    result = np.exp2(exponent, dtype=datatype)
    return result

def nth_root(nth, a, datatype=np.float128):
    if a == 0:
        print('operand is zero')
        return 0
    elif a > 0:
        print('a > 0')
        return naive_root(nth, a, datatype=datatype)
    elif a < 0:
        if a % 2 == 1:
            print('a is odd')
            return -naive_root(nth, np.abs(a))
        else:
            print('a is even')
            return naive_root(nth, np.abs(a))

解决方案

请参见通过对负指数求平方来求幂

无论如何,因为我不在这里先用python或gmpy编写代码,所以先定义一些:

  • pow(x,y)表示由y提供动力的x
  • root(x,y)表示yx -th根

由于这些是反函数,我们可以重写:

  • pow(root(x,y),x)=y

您可以使用它来检查正确性.由于函数是逆的,因此您也可以这样写:

  • pow(x,1/y)=root(y,x)
  • root(1/x,y)=pow(y,x)

因此,如果您获得小数(有理)的根或幂,则可以使用逆函数将其计算为整数.

例如,如果您得到类似root(2/3,5)之类的内容,则需要首先将其分隔为整数:

root(2/3,5)=pow(root(2,5),3)
 ~11.18034 = ~2.236068   ^3
 ~11.18034 = ~11.18034

对于理性根源和权力,您无法获得精确的结果.取而代之的是,将根或幂四舍五入到最接近的可能表示形式,可以使错误最小化或使用pow(x,y) = exp2(y*log2(x))方法.如果使用任何浮点数或定点十进制数,则可以忘记精确的结果,并从头开始选择pow(x,y) = exp2(y*log2(x)) ...

[注释]

我仅假设正操作数 ...如果您将负数加幂或加根,则需要处理整数根和幂(奇/偶)的符号.对于理性,根源和权力没有任何意义(或者至少我们还不了解).

I found the following answer here on Stackoverflow:

https://stackoverflow.com/a/356187/1829329

But it only works for integers as n in nth root:

import gmpy2 as gmpy

result = gmpy.root((1/0.213), 31.5).real
print('result:', result)

results in:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-14-eb4628226deb> in <module>()
      8 
----> 9 result = gmpy.root((1/0.213), 31.5).real
     10 
     11 print('result:', result)

TypeError: root() requires 'mpfr','int' arguments

What is a good and precise way to calculate such a root? (This is the python code representation of some formular, which I need to use to calculate in a lecture.)

EDIT#1

Here is my solution based on Spektre's answer and information from the people over here at http://math.stackexchange.com.

import numpy as np

def naive_root(nth, a, datatype=np.float128):
    """This function can only calculate the nth root, if the operand a is positive."""
    logarithm = np.log2(a, dtype=datatype)
    exponent = np.multiply(np.divide(1, nth, dtype=datatype), logarithm, dtype=datatype)
    result = np.exp2(exponent, dtype=datatype)
    return result

def nth_root(nth, a, datatype=np.float128):
    if a == 0:
        print('operand is zero')
        return 0
    elif a > 0:
        print('a > 0')
        return naive_root(nth, a, datatype=datatype)
    elif a < 0:
        if a % 2 == 1:
            print('a is odd')
            return -naive_root(nth, np.abs(a))
        else:
            print('a is even')
            return naive_root(nth, np.abs(a))

解决方案

see Power by squaring for negative exponents

anyway as I do not code in python or gmpy here some definitions first:

  • pow(x,y) means x powered by y
  • root(x,y) means x-th root of y

As these are inverse functions we can rewrite:

  • pow(root(x,y),x)=y

You can use this to check for correctness. As the functions are inverse you can write also this:

  • pow(x,1/y)=root(y,x)
  • root(1/x,y)=pow(y,x)

So if you got fractional (rational) root or power you can compute it as integer counterpart with inverse function.

Also if you got for example something like root(2/3,5) then you need to separate to integer operands first:

root(2/3,5)=pow(root(2,5),3)
 ~11.18034 = ~2.236068   ^3
 ~11.18034 = ~11.18034

For irational roots and powers you can not obtain precise result. Instead you round the root or power to nearest possible representation you can to minimize the error or use pow(x,y) = exp2(y*log2(x)) approach. If you use any floating point or fixed point decimal numbers then you can forget about precise results and go for pow(x,y) = exp2(y*log2(x)) from the start ...

[Notes]

I assumed only positive operand ... if you got negative number powered or rooted then you need to handle the sign for integer roots and powers (odd/even). For irational roots and powers have the sign no meaning (or at least we do not understand any yet).

这篇关于如何计算浮点数的Python浮点数的根的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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