Fractions with python - python

I'm trying to do this calculation:
from fractions import Fraction
z=4
x=Float(Fraction(1+math.pi,1+2*z**2))
But this results in the following error:
TypeError: both arguments should be Rational instances
If I change pi value for integer value works. But if I use a decimal value shows me that error.
Any idea?
Regards
Thanks

Taken from the documented for the fractions module:
The [two argument constructor] requires that numerator and denominator are instances of numbers.Rational.
In your snippet, 1+math.pi is a float, not an instance of numbers.Rational, hence the TypeError.

Related

Decimal library and round() function

Difference between rounding using Decimal library and rounding using round() function in Python 3.
I don't know whether to use the round() function or use the Decimal library to round numbers
Decimal
from decimal import*
getcontext().prec = 3
print(Decimal(10)/3)
3,33
round()
print(round(10/3,2))
3,33
I hope everyone can answer my questions
They serve different purposes, you can use both. While you use the function round to perform an actual rounding action, as per the docs:
Return number rounded to ndigits precision after the decimal point. If ndigits is omitted or is None, it returns the nearest integer to its input.
With decimal, you can get and set the context for which you want numerical variables to operate (and a lot more, but for the sake of your question, I will limit it to this)
from decimal import *
getcontext()
Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
capitals=1, clamp=0, flags=[], traps=[Overflow, DivisionByZero,
InvalidOperation])
Thus allowing me to set it differently with:
getcontext().rounding = ROUND_UP
With the latter you are not rounding per se, but doing it as a consequence of the context you define.
The module design is centered around three concepts: the decimal number, the context for arithmetic, and signals.
The context for arithmetic is an environment specifying precision, rounding rules, limits on exponents, flags indicating the results of operations, and trap enablers which determine whether signals are treated as exceptions. Rounding options include ROUND_CEILING, ROUND_DOWN, ROUND_FLOOR, ROUND_HALF_DOWN, ROUND_HALF_EVEN, ROUND_HALF_UP, ROUND_UP, and ROUND_05UP.
from decimal import *
print(Decimal("3.33"))
#output
Decimal('3.33')
# These Decimal objects can be converted to float(), int(), etc. and can be fed to round functions as well.
print(round(Decimal("3.33")))
#ouput
3
print(round('3.33'))
#output
TypeError: type str doesn't define __round__ method
round() always take argument as an integer, while you can pass string in Decimal()
You can pass Decimal object in round function as well.
round() documentation https://docs.python.org/3/library/functions.html#round
Decimal() documentation https://docs.python.org/3/library/decimal.html#decimal-objects

Find the base of the power and power with given base in python

I have a number N let's say 5451 and I want to find the base for power 50. How do I do it with python?
The answer is 1.1877622648368 according this website (General Root calculator) But i need to find it with computation.
Second question. If I have the number N 5451, and I know the base 1.1877622648368, how do I find the power?
Taking the n-th root is the same as raising to the power 1/n. This is very simple to do in Python using the ** operator (exponentiation):
>>> 5451**(1/50)
1.1877622648368031
The second one requires a logarithm, which is the inverse of exponentiation. You want to take the base-1.1877622648368031 logarithm of 5451, which is done with the log function in the math module:
>>> import math
>>> math.log(5451, 1.1877622648368031)
50.00000000000001
As you can see, there's some roundoff error. This is unavoidable when working with limited-precision floating point numbers. Apply the round() function to the result if you know that it must be an integer.

Error 34, Result too large

I am trying to print the Fibonacci sequence and it always returns an Overflow error after about the 600th term.
def fib():
import math
from math import sqrt
print "\nFibonacci Sequence up to the term of what?"
n=raw_input(prompt)
if n.isdigit():
if int(n)==0:
return 0
elif int(n)==1:
return 1
else:
n_count=2
print "\n0\n1"
while n_count<int(n):
fib=int(((1+sqrt(5))**n_count-(1-sqrt(5))**n_count)/(2**n_count*sqrt(5)))
print fib
n_count+=1
fib()
else:
print "\nPlease enter a number."
fib()
fib()
When I run this:
Traceback (most recent call last):
File "<pyshell#21>", line 1, in <module>
fib()
File "<pyshell#20>", line 15, in fib
fib=int(((1+sqrt(5))**n_count-(1-sqrt(5))**n_count)/(2**n_count*sqrt(5)))
OverflowError: (34, 'Result too large')
Well, first, let's split that big expression up into smaller ones, so we can see where it's going wrong. And use a debugger or some print statements to see what values are making it go wrong. That way, we're not just taking a stab in the dark.
If you do that, you can tell that (1+sqrt(5)**n_count) is raising this exception when n_count hits 605. Which you can verify pretty easily:
>>> (1+sqrt(5))**604
1.1237044275099689e+308
>>> (1+sqrt(5))**605
OverflowError: (34, 'Result too large')
So, why is that a problem?
Well, Python float values, unlike its integers, aren't arbitrary-sized, they can only hold what an IEEE double can hold:*
>>> 1e308
1e308
>>> 1e309
inf
So, the problem is that one of the terms in your equation is greater than the largest possible IEEE double.
That means you either need to pick a different algorithm,** or get a "big-float" library.
As it happens, Python has a built-in big-float library, in the decimal module. Of course as the name implies, it handles decimal floats, not binary floats, so you'll get different rounding errors if you use it. But you presumably don't care much about rounding errors, given your code.
So:
import decimal
s5 = decimal.Decimal(5).sqrt()
… then …
fib=int(((1+s5)**n_count-(1-s5)**n_count)/(2**n_count*s5))
* In fact, the limits are platform-specific; implementations aren't required to use IEEE doubles for float. So, use sys.float_info to see the max value for your platform. But it's almost always going to be 1.7976931348623157e+308.
** Note that the only advantage of the algorithm you're using over the naive one is that it allows you to approximate the Nth Fibonacci number directly, without calculating the preceding N-1. But since you want to print them all out anyway, you're not getting any advantage. You're just getting the disadvantages—it's an approximation; it's more complicated; it requires floating-point math, which is subject to rounding error; it's slower; it takes more memory; the built-in floating-point types in most languages on most platforms can't hold F(605), … All that for no benefit doesn't seem worth it.
As abarnert pointed out, floats are limited in python. You can see the limit by
>>> import sys
>>> sys.float_info
sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.220446049250313e-16, radix=2, rounds=1)
You will reach some more terms if you divide by 2 before raising to the power:
int(( ((1+sqrt(5))/2)**n_count - ((1-sqrt(5))/2)**n_count)/sqrt(5))
But since Fibonacci sequence grows exponentially, you will soon hit the same wall. Try computing Fibonacci by holding the last two terms and adding them. That way you will use ints.

Can I type 1/2 in sympy python?

I have the hamiltonian for harmonic oscillator where I would like to see (n+1/2) but sympy see 1/2 is zero or if I type 1/2.0 =0.5 . Is it possible to keep as 1/2 and at the same time it maintains as an fraction not a symbol? Thanks,
You need to type Rational(1, 2), or, more concisely, S(1)/2.
See http://docs.sympy.org/latest/tutorial/gotchas.html#two-final-notes-and. 1/2 is entirely Python: no SymPy types are involved. The only way to get Python from doing what it does with int/int (integer division in Python 2 and float division in Python 3 or Python 2 with from __future__ import division) is to use a SymPy type somewhere, which is what both of the above do.

Is there any way to access denominator of a fraction in Python 2

Is there any way to access the denominator in a fraction in Python 2?
For example, I have a variable:
x = fractions.Fraction(4,1)
And I want to access its denominator. How do I do that?
>>> from fractions import Fraction
>>> a = Fraction(1,2)
>>> a.denominator
2
Additionally Python's help() method can be very useful to determine exactly what methods and properties exist for an object. In the example above you could get a help description for the Fraction object by help(Fraction) or help(a) in an interpreter session.

Categories