Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
323 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

equation

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...