Python fractions to float

How to convert rational and decimal number strings to floats in python?

Generally using eval is a bad idea, since it’s a security risk. Especially if the string being evaluated came from outside the system.

+1. eval is completely unnecessary in this case, and I’m glad somebody (other than me, of course) stuck up for what’s right.

Eval is not a security risk unless your co-workers are malicious sociopaths. You don’t need it in this case, but it’s no more a security risk than open source code itself.

Very good. The string is indeed from outside so I need to go safe (and try not to learn bad habits). I was hoping for not needing to parse it but this is not too bad and works like a charm.

As others have pointed out, using eval is potentially a security risk, and certainly a bad habit to get into. (if you don’t think it’s as risky as exec , imagine eval ing something like: __import__(‘os’).system(‘rm -rf /’) )

However, if you have python 2.6 or up, you can use ast.literal_eval , for which the string provided:

may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

Thus it should be quite safe 🙂

How is it possible to eval something as malicious as the example without having coworkers who are seriously deranged? Eval is no more a security risk than access to the shell is a security risk.

Fair point..If you’re not dealing with untrusted input then eval is no risk. I think I’m influenced by this post: phpxmlrpc.sourceforge.net/#security — PHP guys tried twice to solve their problems, before realising that they had to get rid of eval. So .

. I’m inclined to take the position that the easiest way to avoid problems is to get into the habit of using it never. Then, if I do find myself needing eval, at least I’ve got the mental check of breaking one of my rules, which makes me look harder at what I’m doing.

Another option (also only for 2.6 and up) is the fractions module.

>>> from fractions import Fraction >>> Fraction("0.1234") Fraction(617, 5000) >>> Fraction("1/2") Fraction(1, 2) >>> float(Fraction("0.1234")) 0.1234 >>> float(Fraction("1/2")) 0.5 

Use from __future__ import division to get the behavior you want. Then, in a pinch, you can do something like

from __future__ import division strings = ["0.1234", "1/2", "2/3"] numbers = map(eval, strings) 

to get a list of floats out of your strings. If you want to do this the «right» way, don’t use eval() , but instead write a function that accepts a string and calls float() on it if it contains no slash, or parses the string and divides the numerator and denominator if there’s a slash in it.

def parse_float_string(x) parts = x.split('/', 1) if len(parts) == 1: return float(x) elif len(parts) == 2: return float(parts[0])/float(parts[1]) else: raise ValueError 

Then just map(parse_float_string, strings) will get you your list.

Читайте также:  Python command line exit code

Источник

fractions — Rational numbers¶

The fractions module provides support for rational number arithmetic.

A Fraction instance can be constructed from a pair of integers, from another rational number, or from a string.

class fractions. Fraction ( numerator = 0 , denominator = 1 ) ¶ class fractions. Fraction ( other_fraction ) class fractions. Fraction ( float ) class fractions. Fraction ( decimal ) class fractions. Fraction ( string )

The first version requires that numerator and denominator are instances of numbers.Rational and returns a new Fraction instance with value numerator/denominator . If denominator is 0 , it raises a ZeroDivisionError . The second version requires that other_fraction is an instance of numbers.Rational and returns a Fraction instance with the same value. The next two versions accept either a float or a decimal.Decimal instance, and return a Fraction instance with exactly the same value. Note that due to the usual issues with binary floating-point (see Floating Point Arithmetic: Issues and Limitations ), the argument to Fraction(1.1) is not exactly equal to 11/10, and so Fraction(1.1) does not return Fraction(11, 10) as one might expect. (But see the documentation for the limit_denominator() method below.) The last version of the constructor expects a string or unicode instance. The usual form for this instance is:

[sign] numerator ['/' denominator] 

where the optional sign may be either ‘+’ or ‘-’ and numerator and denominator (if present) are strings of decimal digits (underscores may be used to delimit digits as with integral literals in code). In addition, any string that represents a finite value and is accepted by the float constructor is also accepted by the Fraction constructor. In either form the input string may also have leading and/or trailing whitespace. Here are some examples:

>>> from fractions import Fraction >>> Fraction(16, -10) Fraction(-8, 5) >>> Fraction(123) Fraction(123, 1) >>> Fraction() Fraction(0, 1) >>> Fraction('3/7') Fraction(3, 7) >>> Fraction(' -3/7 ') Fraction(-3, 7) >>> Fraction('1.414213 \t\n') Fraction(1414213, 1000000) >>> Fraction('-.125') Fraction(-1, 8) >>> Fraction('7e-6') Fraction(7, 1000000) >>> Fraction(2.25) Fraction(9, 4) >>> Fraction(1.1) Fraction(2476979795053773, 2251799813685248) >>> from decimal import Decimal >>> Fraction(Decimal('1.1')) Fraction(11, 10) 

The Fraction class inherits from the abstract base class numbers.Rational , and implements all of the methods and operations from that class. Fraction instances are hashable , and should be treated as immutable. In addition, Fraction has the following properties and methods:

Читайте также:  Typescript cannot find module import

Changed in version 3.2: The Fraction constructor now accepts float and decimal.Decimal instances.

Changed in version 3.9: The math.gcd() function is now used to normalize the numerator and denominator. math.gcd() always return a int type. Previously, the GCD type depended on numerator and denominator.

Changed in version 3.11: Underscores are now permitted when creating a Fraction instance from a string, following PEP 515 rules.

Changed in version 3.11: Fraction implements __int__ now to satisfy typing.SupportsInt instance checks.

Numerator of the Fraction in lowest term.

Denominator of the Fraction in lowest term.

Return a tuple of two integers, whose ratio is equal to the Fraction and with a positive denominator.

Alternative constructor which only accepts instances of float or numbers.Integral . Beware that Fraction.from_float(0.3) is not the same value as Fraction(3, 10) .

From Python 3.2 onwards, you can also construct a Fraction instance directly from a float .

Alternative constructor which only accepts instances of decimal.Decimal or numbers.Integral .

From Python 3.2 onwards, you can also construct a Fraction instance directly from a decimal.Decimal instance.

Finds and returns the closest Fraction to self that has denominator at most max_denominator. This method is useful for finding rational approximations to a given floating-point number:

>>> from fractions import Fraction >>> Fraction('3.1415926535897932').limit_denominator(1000) Fraction(355, 113) 

or for recovering a rational number that’s represented as a float:

>>> from math import pi, cos >>> Fraction(cos(pi/3)) Fraction(4503599627370497, 9007199254740992) >>> Fraction(cos(pi/3)).limit_denominator() Fraction(1, 2) >>> Fraction(1.1).limit_denominator() Fraction(11, 10) 
>>> from math import floor >>> floor(Fraction(355, 113)) 3 

Returns the least int >= self . This method can also be accessed through the math.ceil() function.

__round__ ( ) ¶ __round__ ( ndigits )

The first version returns the nearest int to self , rounding half to even. The second version rounds self to the nearest multiple of Fraction(1, 10**ndigits) (logically, if ndigits is negative), again rounding half toward even. This method can also be accessed through the round() function.

The abstract base classes making up the numeric tower.

Источник

Fractions (rational numbers) in Python

You can handle fractions (rational numbers) with the fractions module in Python.

Читайте также:  METANIT.COM

This article describes the following contents.

  • The Fraction constructor
  • Get numerator and denominator
  • Calculate and compare fractions
  • Convert a fraction to a floating-point number: float()
  • Convert a fraction to a string: str()
  • Get rational approximations: limit_denominator()

See the following article on how to find the greatest common divisor and least common multiple.

The Fraction constructor

There are several ways to create a Fraction instance. Note that in all cases, the result is automatically reduced (simplified).

Specify numerator and denominator as integers

The denominator is considered 1 if omitted.

from fractions import Fraction print(Fraction(1, 3)) # 1/3 print(Fraction(2, 6)) # 1/3 print(Fraction(3)) # 3 

Floating-point number ( float )

print(Fraction(0.25)) # 1/4 print(Fraction(0.33)) # 5944751508129055/18014398509481984 

If you want to approximate by specifying the maximum denominator, use the limit_denominator() method described below.

String ( str )

print(Fraction('2/5')) # 2/5 print(Fraction('16/48')) # 1/3 

Get numerator and denominator

You can get the numerator and denominator with the numerator and denominator attributes of Fraction . They cannot be changed.

a = Fraction(1, 3) print(a) # 1/3 print(a.numerator) print(type(a.numerator)) # 1 # print(a.denominator) print(type(a.denominator)) # 3 # # a.numerator = 7 # AttributeError: can't set attribute 

Calculate and compare fractions

You can calculate Fraction with arithmetic operators.

result = Fraction(1, 6) ** 2 + Fraction(1, 3) / Fraction(1, 2) print(result) print(type(result)) # 25/36 # 

You can also use the comparison operator.

print(Fraction(7, 13) > Fraction(8, 15)) # True 

Convert a fraction to a floating-point number: float()

You can convert Fraction to a floating-point number with float() .

a_f = float(a) print(a_f) print(type(a_f)) # 0.3333333333333333 # 

The result of an operation between Fraction and float is automatically converted to float .

b = a + 0.1 print(b) print(type(b)) # 0.43333333333333335 # 

Convert a fraction to a string: str()

You can convert Fraction to a string with str() .

a_s = str(a) print(a_s) print(type(a_s)) # 1/3 # 

Get rational approximations: limit_denominator()

You can get a rational approximation with the limit_denominator() method.

The limit_denominator() method returns Fraction whose denominator is less than or equal to the max_denominator parameter. The default is max_denominator=1000000 .

Approximate Pi and Napier number e

pi = Fraction(3.14159265359) print(pi) # 3537118876014453/1125899906842624 print(pi.limit_denominator(10)) print(pi.limit_denominator(100)) print(pi.limit_denominator(1000)) # 22/7 # 311/99 # 355/113 e = Fraction(2.71828182846) print(e) # 6121026514870223/2251799813685248 print(e.limit_denominator(10)) print(e.limit_denominator(100)) print(e.limit_denominator(1000)) # 19/7 # 193/71 # 1457/536 

Convert repeating decimals to fractions

a = Fraction(0.565656565656) print(a) # 636872674577009/1125899906842624 print(a.limit_denominator()) # 56/99 a = Fraction(0.3333) print(a) # 6004199023210345/18014398509481984 print(a.limit_denominator()) print(a.limit_denominator(100)) # 3333/10000 # 1/3 

Источник

Оцените статью