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

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

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

Here is something I use that seems to work with any number just fine:
root = number**(1/nthroot)
print(root)
It works with any number data type.

Related

Error with quantifier in Z3Py

I would like Z3 to check whether it exists an integer t that satisfies my formula. I'm getting the following error:
Traceback (most recent call last):
File "D:/z3-4.6.0-x64-win/bin/python/Expl20180725.py", line 18, in <module>
g = ForAll(t, f1(t) == And(t>=0, t<10, user[t].rights == ["read"] ))
TypeError: list indices must be integers or slices, not ArithRef
Code:
from z3 import *
import random
from random import randrange
class Struct:
def __init__(self, **entries): self.__dict__.update(entries)
user = [Struct() for i in range(10)]
for i in range(10):
user[i].uid = i
user[i].rights = random.choice(["create","execute","read"])
s=Solver()
f1 = Function('f1', IntSort(), BoolSort())
t = Int('t')
f2 = Exists(t, f1(t))
g = ForAll(t, f1(t) == And(t>=0, t<10, user[t].rights == ["read"] ))
s.add(g)
s.add(f2)
print(s.check())
print(s.model())
You are mixing and matching Python and Z3 expressions, and while that is the whole point of Z3py, it definitely does not mean that you can mix/match them arbitrarily. In general, you should keep all the "concrete" parts in Python, and relegate the symbolic parts to "z3"; carefully coordinating the interaction in between. In your particular case, you are accessing a Python list (your user) with a symbolic z3 integer (t), and that is certainly not something that is allowed. You have to use a Z3 symbolic Array to access with a symbolic index.
The other issue is the use of strings ("create"/"read" etc.) and expecting them to have meanings in the symbolic world. That is also not how z3py is intended to be used. If you want them to mean something in the symbolic world, you'll have to model them explicitly.
I'd strongly recommend reading through http://ericpony.github.io/z3py-tutorial/guide-examples.htm which is a great introduction to z3py including many of the advanced features.
Having said all that, I'd be inclined to code your example as follows:
from z3 import *
import random
Right, (create, execute, read) = EnumSort('Right', ('create', 'execute', 'read'))
users = Array('Users', IntSort(), Right)
for i in range(10):
users = Store(users, i, random.choice([create, execute, read]))
s = Solver()
t = Int('t')
s.add(t >= 0)
s.add(t < 10)
s.add(users[t] == read)
r = s.check()
if r == sat:
print s.model()[t]
else:
print r
Note how the enumerated type Right in the symbolic land is used to model your "permissions."
When I run this program multiple times, I get:
$ python a.py
5
$ python a.py
9
$ python a.py
unsat
$ python a.py
6
Note how unsat is produced, if it happens that the "random" initialization didn't put any users with a read permission.

How to detect overflow while arithmetic in python?

I am working on a analysis problem in python in which I have to work on big floating point numbers and was performing some operations on it. My codes seems to break in between; looking carefully I found that sometimes a simple add operation would return inf it must be an overflow.
>>> a = float(2**1022) + float(2**1023)
>>> print a
1.348269851146737e+308
>>> a = float(2**1023) + float(2**1023)
>>> print a
inf
>>>
How do we check for overflow in python while floating point operation since instead of giving a OverflowError it silently gives a value inf.
I can only imagine checking if abs(a)==float('inf'): raise OverflowError()…
Use an arbitrary precision library like GMPY and you won't need to worry.
Disclaimer: I maintain gmpy2.
The gmpy2 library supports both arbitrary precision (to decrease the occurrences of overflow) and the ability to trap on floating point events. Here is an example of modify the context to automatically raise an exception when an overflow occurs.
>>> import gmpy2
>>> from gmpy2 import get_context,set_context, ieee, mpfr
>>> set_context(ieee(64))
>>> get_context()
context(precision=53, real_prec=Default, imag_prec=Default,
round=RoundToNearest, real_round=Default, imag_round=Default,
emax=1024, emin=-1073,
subnormalize=True,
trap_underflow=False, underflow=False,
trap_overflow=False, overflow=False,
trap_inexact=False, inexact=False,
trap_invalid=False, invalid=False,
trap_erange=False, erange=False,
trap_divzero=False, divzero=False,
trap_expbound=False,
allow_complex=False)
>>> get_context().trap_overflow=True
>>> get_context()
context(precision=53, real_prec=Default, imag_prec=Default,
round=RoundToNearest, real_round=Default, imag_round=Default,
emax=1024, emin=-1073,
subnormalize=True,
trap_underflow=False, underflow=False,
trap_overflow=True, overflow=False,
trap_inexact=False, inexact=False,
trap_invalid=False, invalid=False,
trap_erange=False, erange=False,
trap_divzero=False, divzero=False,
trap_expbound=False,
allow_complex=False)
>>> mpfr(2**1023) + mpfr(2**1023)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
gmpy2.OverflowResultError: 'mpfr' overflow in "addition"
>>>

Handling exception - negative square root in python

I am trying to write a piece of code to handle the exception of negative square roots, since I only want a positive result. My code is:
def sqRoot(x):
try:
result = (x)**0.5
except ValueError:
result = "This is a negative root"
except TypeError:
result = "Please enter a number"
return result
For some reason, when I run this code using the call
x = sqRoot(-200)
I don't get the error, but instead python is giving me the result as a complex number. I can't seem to see the error in my code.
Shifting this discussion from the comments...
In Python 3.0 the behaviour of the power operator changed. In earlier versions of python, raising a negative number to a fractional power raised a ValueError exception, but in Python 3 it yields a complex result.
An alternative for finding the square root is the python is the math.sqrt function. In Python 3 this raises a ValueError exception when used with a negative number:
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:43:06) [MSC v.1600 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import math
>>> math.sqrt(-200)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: math domain error
If python 3 returns a complex number and that is not what you want, you can always achieve the desired output with an if statement:
def sqRoot(x):
if not isinstance(x, (int, long, float)):
return "Please enter a number"
if x < 0:
return "This is a negative root"
return (x)**0.5
Since in python 3, the square root of a negative number is defined (as complex), you will have to test for it yourself:
def sqRoot(x):
if not type(x) in [int, long, float]:
result = "Please enter a number"
elif x < 0:
result = "This is a negative root"
else:
result = (x)**0.5
return result
By the way, I don't think that it's good programming practice to have the function return numbers in one case, and strings in the other. I think that is better done by raising errors.

The fourth root of (12) or any other number in Python 3

I'm trying to make a simple code for power 12 to 4(12 ** 4) .
I have the output num (20736) but when I want to figure returns (20736) to its original value (12). I don't know how to do that in Python ..
in Real mathematics I do that by the math phrase {12؇}
The question is how to make {12؇} in Python ??
I'm using sqrt() but sqrt only for power 2
#!/usr/bin/env python3.3
import math
def pwo():
f=12 ** 4 #f =20736 #
c= # should c = 12 #
return f,c
print pwo()
def f(num):
return num**0.25
or
import math
def f(num):
return math.sqrt(math.sqrt(num))
For scientific purposes (where you need a high level of precision), you can use numpy:
>>> def root(n, r=4):
... from numpy import roots
... return roots([1]+[0]*(r-1)+[-n])
...
>>> print(root(12))
[ -1.86120972e+00+0.j -3.05311332e-16+1.86120972j
-3.05311332e-16-1.86120972j 1.86120972e+00+0.j ]
>>>
The output may look strange, but it can be used just as you would use a list. Furthermore, the above function will allow you to find any root of any number (I put the default for r equal to 4 since you asked for the fourth root specifically). Finally, numpy is a good choice because it will return the complex numbers that will also satisfy your equations.

Formatting Complex Numbers

For a project in one of my classes we have to output numbers up to five decimal places.It is possible that the output will be a complex number and I am unable to figure out how to output a complex number with five decimal places. For floats I know it is just:
print "%0.5f"%variable_name
Is there something similar for complex numbers?
You could do it as is shown below using the str.format() method:
>>> n = 3.4+2.3j
>>> n
(3.4+2.3j)
>>> '({0.real:.2f} + {0.imag:.2f}i)'.format(n)
'(3.40 + 2.30i)'
>>> '({c.real:.2f} + {c.imag:.2f}i)'.format(c=n)
'(3.40 + 2.30i)'
To make it handle both positive and negative imaginary portions properly, you would need a (even more) complicated formatting operation:
>>> n = 3.4-2.3j
>>> n
(3.4-2.3j)
>>> '({0:.2f} {1} {2:.2f}i)'.format(n.real, '+-'[n.imag < 0], abs(n.imag))
'(3.40 - 2.30i)'
Update - Easier Way
Although you cannot use f as a presentation type for complex numbers using the string formatting operator %:
n1 = 3.4+2.3j
n2 = 3.4-2.3j
try:
print('test: %.2f' % n1)
except Exception as exc:
print('{}: {}'.format(type(exc).__name__, exc))
Output:
TypeError: float argument required, not complex
You can however use it with complex numbers via the str.format() method. This isn't explicitly documented, but is implied by the Format Specification Mini-Language documentation which just says:
'f'  Fixed point. Displays the number as a fixed-point number. The default precision is 6.
. . .so it's easy to overlook.
In concrete terms, the following works in both Python 2.7.14 and 3.4.6:
print('n1: {:.2f}'.format(n1))
print('n2: {:.2f}'.format(n2))
Output:
n1: 3.10+4.20j
n2: 3.10-4.20j
This doesn't give you quite the control the code in my original answer does, but it's certainly much more concise (and handles both positive and negative imaginary parts automatically).
Update 2 - f-strings
Formatted string literals (aka f-strings) were added in Python 3.6, which means it could also be done like this in that version or later:
print(f'n1: {n1:.2f}') # -> n1: 3.40+2.30j
print(f'n2: {n2:.3f}') # -> n2: 3.400-2.300j
In Python 3.8.0, support for an = specifier was added to f-strings, allowing you to write:
print(f'{n1=:.2f}') # -> n1=3.40+2.30j
print(f'{n2=:.3f}') # -> n2=3.400-2.300j
Neither String Formatting Operations - i.e. the modulo (%) operator) -
nor the newer str.format() Format String Syntax support complex types.
However it is possible to call the __format__ method of all built in numeric types directly.
Here is an example:
>>> i = -3 # int
>>> l = -33L # long (only Python 2.X)
>>> f = -10./3 # float
>>> c = - 1./9 - 2.j/9 # complex
>>> [ x.__format__('.3f') for x in (i, l, f, c)]
['-3.000', '-33.000', '-3.333', '-0.111-0.222j']
Note, that this works well with negative imaginary parts too.
For questions like this, the Python documentation should be your first stop. Specifically, have a look at the section on string formatting. It lists all the string format codes; there isn't one for complex numbers.
What you can do is format the real and imaginary parts of the number separately, using x.real and x.imag, and print it out in a + bi form.
>>> n = 3.4 + 2.3j
>>> print '%05f %05fi' % (n.real, n.imag)
3.400000 2.300000i
As of Python 2.6 you can define how objects of your own classes respond to format strings. So, you can define a subclass of complex that can be formatted. Here's an example:
>>> class Complex_formatted(complex):
... def __format__(self, fmt):
... cfmt = "({:" + fmt + "}{:+" + fmt + "}j)"
... return cfmt.format(self.real, self.imag)
...
>>> z1 = Complex_formatted(.123456789 + 123.456789j)
>>> z2 = Complex_formatted(.123456789 - 123.456789j)
>>> "My complex numbers are {:0.5f} and {:0.5f}.".format(z1, z2)
'My complex numbers are (0.12346+123.45679j) and (0.12346-123.45679j).'
>>> "My complex numbers are {:0.6f} and {:0.6f}.".format(z1, z2)
'My complex numbers are (0.123457+123.456789j) and (0.123457-123.456789j).'
Objects of this class behave exactly like complex numbers except they take more space and operate more slowly; reader beware.
Check this out:
np.set_printoptions(precision=2) # Rounds up to 2 decimals all float expressions
I've successfully printed my complexfloat's expressions:
# Show poles and zeros
print( "zeros = ", zeros_H , "\n")
print( "poles = ", poles_H )
out before:
zeros = [-0.8 +0.6j -0.8 -0.6j -0.66666667+0.j ]
poles = [-0.81542318+0.60991027j -0.81542318-0.60991027j -0.8358203 +0.j ]
out after:
zeros = [-0.8 +0.6j -0.8 -0.6j -0.67+0.j ]
poles = [-0.82+0.61j -0.82-0.61j -0.84+0.j ]

Categories