简体   繁体   English

如何在python中使用整数运算将分数转换为浮点数?

[英]How do I use integer arithmetic to convert fractions into floating point numbers in python?

What I need to do is use integer arithmetic to convert fractions into floating point numbers. 我需要做的是使用整数运算将分数转换为浮点数。 The number of decimal places needed is specified as a variable DECIMALS . 所需的小数位数被指定为变量DECIMALS Each fraction is contained in a tuple of integers, for example (1, 3) . 每个分数包含在整数元组中,例如(1, 3) The first item is the numerator and the second is the denominator. 第一项是分子,第二项是分母。 The tuples are contained in a list called fractions . 元组包含在名为fractions的列表中。

This is my code so far: 到目前为止这是我的代码:

fractions = [(1,7), (2,3), (22,7), (7001,7), (9,3), (611951,611953), (1,11), (1,7689585)]

DECIMALS = 10**40 # 40 decimal places

for fraction in fractions:  
     x =  DECIMALS*fraction[0]/fraction[1]
     print x

When i run the code this is what i get: 当我运行代码时,这就是我得到的:

1428571428571428571428571428571428571428
6666666666666666666666666666666666666666
31428571428571428571428571428571428571428   
10001428571428571428571428571428571428571428
30000000000000000000000000000000000000000
9999967317751526669531810449495304377950
909090909090909090909090909090909090909
1300460297922449651053990559958697

The problem is that I need to format this into the correct decimal format. 问题是我需要将其格式化为正确的十进制格式。 What I tried was 我试过的是

print "0.%.40d" % (x)

But of course this will only help me with the first 2 decimals; 但是,这当然只能帮助我获得前2位小数; the rest will be wrong. 其余的都是错的。 I thought about dividing it up so I can calculate the fractions indivdually to make them easier to format, but I have no idea how to do this. 我考虑将其分开,以便我可以单独计算分数以使它们更容易格式化,但我不知道如何做到这一点。 The catch is that all the fractions need to be processed by the same code. 问题是所有分数都需要由相同的代码处理。 I also want it to be rounded properly but thats not a big deal right now. 我也希望它能够正确地完成,但现在这不是什么大问题。

You mean something like this: 你的意思是这样的:

from fractions import Fraction
import decimal

decimal.getcontext().prec = 50

fractions = [(1,7), (2,3), (22,7), (7001,7), (9,3), (611951,611953), (1,11),(1,7689585)]

su=Fraction(0)
for i, t in enumerate(fractions,1):
    f=Fraction(*t)
    su+=Fraction(*t)
    d=decimal.Decimal(f.numerator) / decimal.Decimal(f.denominator)
    print '{} becomes {}'.format(t,f)
    print '\tfloat of that is: {}'.format(float(f))
    print '\tDecimal: {}'.format(d)
    print '\t{} elements cum sum of the list: {}\n'.format(i,su)

Prints: 打印:

(1, 7) becomes 1/7
    float of that is: 0.142857142857
    Decimal: 0.14285714285714285714285714285714285714285714285714
    1 elements cum sum of the list: 1/7

(2, 3) becomes 2/3
    float of that is: 0.666666666667
    Decimal: 0.66666666666666666666666666666666666666666666666667
    2 elements cum sum of the list: 17/21

(22, 7) becomes 22/7
    float of that is: 3.14285714286
    Decimal: 3.1428571428571428571428571428571428571428571428571
    3 elements cum sum of the list: 83/21

(7001, 7) becomes 7001/7
    float of that is: 1000.14285714
    Decimal: 1000.1428571428571428571428571428571428571428571429
    4 elements cum sum of the list: 21086/21

(9, 3) becomes 3
    float of that is: 3.0
    Decimal: 3
    5 elements cum sum of the list: 21149/21

(611951, 611953) becomes 611951/611953
    float of that is: 0.999996731775
    Decimal: 0.99999673177515266695318104494953043779505942449829
    6 elements cum sum of the list: 12955044968/12851013

(1, 11) becomes 1/11
    float of that is: 0.0909090909091
    Decimal: 0.090909090909090909090909090909090909090909090909091
    7 elements cum sum of the list: 142518345661/141361143

(1, 7689585) becomes 1/7689585
    float of that is: 1.30046029792e-07
    Decimal: 1.3004602979224496510539905599586973809379829990825E-7
    8 elements cum sum of the list: 121767437017889092/120778724977295

The fraction module allows you to work with rational numbers (without converting to a float). 分数模块允许您使用有理数(不转换为浮点数)。 Once you have put them into a Fraction class, you can do arithmetic with them (just like in grade school) 将它们放入Fraction类后,就可以对它们进行算术运算(就像在小学一样)

Like this: 像这样:

>>> Fraction(1,3) + Fraction(3,4)
Fraction(13, 12)
>>> Fraction(1,3) + Fraction(1,6)
Fraction(1, 2)
>>> Fraction(1,2).numerator
1
>>> Fraction(1,2).denominator
2

The Fraction module is part of default Python distribution (since 2.6). Fraction模块是默认Python发行版的一部分(自2.6起)。

To convert that to a float, do float(Fraction(17,18)) for example or use Fraction.numerator and Fraction().denominator in a Decimal class variable for arbitrary precision conversion. 要将其转换为浮点数,请执行float(Fraction(17,18))或在Decimal类变量中使用Fraction.numeratorFraction().denominator进行任意精度转换。

Like so: 像这样:

>>> decimal.Decimal(su.numerator) / decimal.Decimal(su.denominator)
Decimal('1008.186144047968368606384293')

or: 要么:

>>> float(su.numerator) / su.denominator
1008.1861440479684

Avoid floating point numbers in the first place. 首先避免使用浮点数。

>>> decimal.getcontext().prec = 50
>>> [str((decimal.Decimal(x) / decimal.Decimal(y)).quantize(decimal.Decimal(10) ** -40)) for (x, y) in FRACTIONS]
['0.1428571428571428571428571428571428571429', '0.6666666666666666666666666666666666666667', '3.1428571428571428571428571428571428571429', '1000.1428571428571428571428571428571428571429', '3.0000000000000000000000000000000000000000', '0.9999967317751526669531810449495304377951', '0.0909090909090909090909090909090909090909', '1.300460297922449651053990559958697E-7']

If it strictly formatting, as implied by your question, you could, of course, do this with integers and strings alone: 如果严格格式化,正如您的问题所暗示的那样,当然,您可以单独使用整数和字符串来执行此操作:

def intF(n, d, l=40):
    s=str(n*10**l / d)
    if len(s) < l:
        return '0.{:0>{width}}'.format(s,width=l)
    if len(s) > l:
        return s[0:len(s)-l]+'.'+s[len(s)-l:] 

    return '0.'+s


for f in [(1,7), (2,3), (22,7), (7001,7), (9,3), 
          (611951,611953), (1,11),(1,7689585)]:
    print intF(*f)
    print float(f[0]) / f[1]
    print 

Output: 输出:

0.1428571428571428571428571428571428571428
0.142857142857

0.6666666666666666666666666666666666666666
0.666666666667

3.1428571428571428571428571428571428571428
3.14285714286

1000.1428571428571428571428571428571428571428
1000.14285714

3.0000000000000000000000000000000000000000
3.0

0.9999967317751526669531810449495304377950
0.999996731775

0.0909090909090909090909090909090909090909
0.0909090909091

0.0000001300460297922449651053990559958697
1.30046029792e-07

The last digit will not correctly round and it will not handle edge cases ('inf', 'NaN', division by zero, etc) correctly. 最后一个数字将无法正确舍入,它将无法正确处理边缘情况('inf','NaN',除以零等)。

Works in a pinch I suppose. 我想是在紧要关头工作。

Why not use the batteries included though, like Decimal or Fraction? 为什么不使用包括的电池,如十进制或分数?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在python中将浮点数转换为整数? - How can I convert a floating point number to an integer in python? 如何在不使用小数、分数或任何其他外部库的情况下修复浮点数中的 Python 舍入错误? - How to fix Python rounding error in Floating Point numbers without using decimal, fractions or any other external libraries? 如何在 Python 中将货币字符串转换为浮点数? - How do I convert a currency string to a floating point number in Python? 如何设置浮点精度以避免Python中的浮点运算错误? - How can I set floating point precision to avoid floating point arithmetic error in Python? 如何正确处理Python中的浮点运算? - How to correctly deal with floating point arithmetic in Python? 如何遍历包含 Python 中浮点数列表的文件? - How do I iterate through a file containing a list of floating point numbers in Python? Python:读入文件,其中数字为分数或浮动以视为浮点数 - Python: Read in file with numbers that are fractions or floating to treat as floating numbers 如何将 dataframe 日期转换为浮点数? - How to convert dataframe dates into floating point numbers? Python浮点数和整数 - Python Floating and Integer Numbers 如何将 Sympy 表达式转换为浮点数? - How do I convert a Sympy expression to a floating point number?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM