How to calculate Python float-number-th root of float number

2024/11/18 13:39:13

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 gmpyresult = 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).real10 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 npdef 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 resultdef nth_root(nth, a, datatype=np.float128):if a == 0:print('operand is zero')return 0elif 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))
Answer

If you are willing to use Python 3.x, the native pow() will do exactly what you want by just using root(x,y) = pow(x,1/y). It will automatically return a complex result if that is appropriate.

Python 3.4.3 (default, Sep 27 2015, 20:37:11)
[GCC 5.2.1 20150922] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> pow(1/0.213, 1/31.5)
1.0503191465568489
>>> pow(1/0.213, -1/31.5)
0.952091565004975
>>> pow(-1/0.213, -1/31.5)
(0.9473604081457588-0.09479770688958634j)
>>> pow(-1/0.213, 1/31.5)
(1.045099874779588+0.10457801566102139j)
>>>

Returning a complex result instead of raising a ValueError is one of changes in Python 3. If you want the same behavior with Python 2, you can use gmpy2 and enable complex results.

>>> import gmpy2
>>> gmpy2.version()
'2.0.5'
>>> gmpy2.get_context().allow_complex=True
>>> pow(1/gmpy2.mpfr("0.213"), 1/gmpy2.mpfr("31.5"))
mpfr('1.0503191465568489')
>>> pow(-1/gmpy2.mpfr("0.213"), 1/gmpy2.mpfr("31.5"))
mpc('1.0450998747795881+0.1045780156610214j')
>>> pow(-1/gmpy2.mpfr("0.213"), -1/gmpy2.mpfr("31.5"))
mpc('0.94736040814575884-0.094797706889586358j')
>>> pow(1/gmpy2.mpfr("0.213"), -1/gmpy2.mpfr("31.5"))
mpfr('0.95209156500497505')
>>> 
https://en.xdnf.cn/q/118664.html

Related Q&A

Need help making a Hilbert Curve using numbers in Python

I want to make a function that will create a Hilbert Curve in python using numbers. The parameters for the function would be a number and that will tell the function how many times it should repeat. To…

How do I separate each list [closed]

Its difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying thi…

Why python doesnt see the members of quantumCircuit class qiskit

I`m trying to learn the programming on quantum computers. I have installed qiskit in VS Code (all qiskit extentions available in VS Code market) , python compilator (from Vs Code market "Python&qu…

Compare multiple lines in a text file using python

Im writing a program that is time tracking report that reports the time that was spent in each virtual machine, I`m having a problem comparing the txt file cause the only thing that changes are the num…

Error installing eomaps through conda and pip

I am getting the following error output when trying to install eomaps using Conda. I dont know how to solve this. I have also tried the same using pip but it didnt seem to solve the problem. Here is th…

DFS on a graph using a python generator

I am using a generator to do a full search on a graph, the real data set is fairly large, here is a portion of the code i wrote on a small data set:class dfs:def __init__(self):self.start_nodes = [1,2]…

Importing test libraries failed. No module named a

I have a folder /example which contains /Libs which further contains different folders /a, /b each containing python libraries. I am trying to run a robot framework code from /example.The error it show…

Sorting characters by count using PHP or Python

I have a string of charactersabcdefghijklmnopqrstuvwxyz_ I want to take this string of characters and sort them by the number of times they appear in a large block of characters. For example: cwrxwzb…

Save user first_name as default value for model django

I have an article model with author variable which I want to save as the users first and last name. I use custom user model called Account. author = models.CharField(author,max_length=50 default=User.f…

How to compare two imagefile from two different files in python

I would like to create a program that compares two images. I need to take images from two different folders and compare that images if they are same or not. Then I want to print out as same or differen…