Converting an improper fraction to a mixed number with python

梦想与她 提交于 2019-12-02 02:21:50

问题


I need to us python to convert an improper fraction to a mixed number or even a float to a mixed number. My code is as follows:

from fractions import Fraction
numerator = int(input("Enter numerator ") )
denominator = int(input("Enter denominator ") )
num = numerator / denominator
num = Fraction(num) 
print(num)

If input is 5 and 4, the output is '5/4' not a mixed number.


回答1:


You can use the divide and modulo operators to print this:

The integer part is numerator // denominator.

The numerator of the proper fraction remainder is numerator % denominator.

And, of course, the denominator doesn't change.

>>> num = 5
>>> den = 4
>>> print(' %d %d/%d' % (num // den, num % den, den))
 1 1/4

Floats are a bit more difficult, because you have to figure out the denominator, and it's usually not going to be exact. There are two basic ways (and several fancier variants) to do this. You can either loop up to a maximum denominator and pick the one that gives you the lowest error, or you can choose a maximum acceptable error, and loop until you find a denominator that gives you a result below it. Sample code to do the latter is as follows:

def approximate_frac(src, epsilon):
    d = 0.0
    while 1:
        d += 1.0
        n = int(src * d)
        info = [(abs(n / d - src), n) for n in (n, n+1)]
        info.sort()
        err, n = info[0]
        if err < epsilon:
            return n, int(d)

print(approximate_frac(1.0/3.0, 0.001))
print(approximate_frac(2.0/17.0, 0.001))

This results in:

(1, 3)
(2, 17)



回答2:


from fractions import Fraction
def convert_to_mixed_numeral(num):
    """Format a number as a mixed fraction.

    Examples:
        convert_to_mixed_numeral('-55/10') # '-5 1/2'
        convert_to_mixed_numeral(-55/10) # '-5 1/2'
        convert_to_mixed_numeral(-5.5) # '-5 1/2'

    Args:
        num (int|float|str): The number to format. It is coerced into a string.

    Returns:
        str: ``num`` formatted as a mixed fraction.

    """
    num = Fraction(str(num)) # use str(num) to prevent floating point inaccuracies
    n, d = (num.numerator, num.denominator)
    m, p = divmod(abs(n), d)
    if n < 0:
        m = -m
    return '{} {}/{}'.format(m, p, d) if m != 0 and p > 0 \
        else '{}'.format(m) if m != 0 \
        else '{}/{}'.format(n, d)

The function can be used by passing it the numerator and denominator as a number, string, or Fraction instance. Or it could be modified to take in the numerator and denominator as separate variables.




回答3:


Try to implement it manually:

  a = numerator // denominator 
  b = numerator % denominator
  print '{} {}/{}'.format(a, b, denominator)

Currently you are just printing 'x/b', if the input is a float do the adequate translation first.

Hope it can help.



来源:https://stackoverflow.com/questions/32085047/converting-an-improper-fraction-to-a-mixed-number-with-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!