How to subtract fractions in python

Last update on August 19 2022 21:51:39 (UTC/GMT +8 hours)

Python Math: Exercise-46 with Solution

Write a Python program to add, subtract, multiply and divide two fractions.

Sample Solution:-

Python Code:

import fractions

f1 = fractions.Fraction(2, 3)
f2 = fractions.Fraction(3, 7)

print('{} + {} = {}'.format(f1, f2, f1 + f2))
print('{} - {} = {}'.format(f1, f2, f1 - f2))
print('{} * {} = {}'.format(f1, f2, f1 * f2))
print('{} / {} = {}'.format(f1, f2, f1 / f2))

Sample Output:

2/3 + 3/7 = 23/21                                                                                             
2/3 - 3/7 = 5/21                                                                                              
2/3 * 3/7 = 2/7                                                                                               
2/3 / 3/7 = 14/9

Flowchart:

How to subtract fractions in python

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to create the fraction instances of decimal numbers.
Next: Write a Python program to convert a floating point number (PI) to an approximate rational value on the various denominator.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Python: Tips of the Day

Find the most frequent element in a list:

test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4]
print(max(set(test), key = test.count))

|


  • Exercises: Weekly Top 12 Most Popular Topics
  • Pandas DataFrame: Exercises, Practice, Solution
  • Conversion Tools
  • JavaScript: HTML Form Validation
  • SQL Exercises, Practice, Solution - SUBQUERIES
  • C Programming Exercises, Practice, Solution : For Loop
  • Python Exercises, Practice, Solution
  • Python Data Type: List - Exercises, Practice, Solution
  • C++ Basic: Exercises, Practice, Solution
  • SQL Exercises, Practice, Solution - exercises on Employee Database
  • SQL Exercises, Practice, Solution - exercises on Movie Database
  • SQL Exercises, Practice, Solution - exercises on Soccer Database
  • C Programming Exercises, Practice, Solution : Recursion


I am trying to add two fractions in python

if input 1/4 + 1/4, I am expecting 1/2 result

I built a fraction class with an __add__ method for addition

from fractions import gcd

class fraction:
    def __init__(self, numerator, denominator):
        self.num = numerator
        self.deno = denominator
    def __add__(self, other):
        self.sumOfn = self.num + other.num
        self.sumOfd = gcd(self.deno,other.deno)
        return(self.sumOfn, self.sumOfd)



print(fraction(1,4)+fraction(1,4))

However I am getting 2,4 as output, which is actually 1/2, just not simplified. How could I fix that problem ?

from AddFraction import PlusFraction


class MinusFraction(PlusFraction):

    
    def __init__(self, fractions):
        super().__init__(fractions)

    
    def doSubtract(self):
        
        self.canoniseFraction()

        
        
        self.answer = self.new_numerators[0]
        for count in range(1, len(self.new_numerators)): self.answer -= self.new_numerators[count]

        return {'numerator':self.answer, 'denominator':self.lcm}


from SubtractFraction import MinusFraction


 
 
numerators   = [9, 3, 5, 7]
denominators = [2, 4, 12, 18]
fractions = {'numerators':numerators, 'denominators':denominators}

print('\n    Solving:\n')

for numerator in fractions['numerators']: print('{:13d}'.format(numerator), end='')
print('{}{:>12}'.format('\n'' '), end='')
for wasted in range(len(numerators)-1): print('{}'.format('-     +      '), end='')
print('{:>1}'.format('-'))
for denominator in fractions['denominators']: print('{:13d}'.format(denominator), end=''
print('\n\n')


sub_fract = MinusFraction(fractions)
fraction = sub_fract.doSubtract()

print('{:25d}'.format(fraction['numerator']))
print('{:>25}'.format('Answer   =   -'))
print('{:25d}'.format(fraction['denominator']))

print('\n\n')

How do you add and subtract fractions in Python?

Algorithm.
Initialize variables of numerator and denominator..
Take user input of two fraction..
Find numerator using this condition (n1*d2) +(d1*n2 ) where n1,n2 are numerator and d1 and d2 are denominator..
Find denominator using this condition (d1*d2) for lcm..
Calculate GCD of a this new numerator and denominator..

How do you solve fractions in Python?

You have two options:.
Use float.as_integer_ratio() : >>> (0.25).as_integer_ratio() (1, 4) (as of Python 3.6, you can do the same with a decimal. Decimal() object.).
Use the fractions.Fraction() type: >>> from fractions import Fraction >>> Fraction(0.25) Fraction(1, 4).

How do you reduce a Fraction in Python?

Reduce Fractions Function Python.
A function that reduces/simplifies fractions using the Euclidean Algorithm, in Python..
def reducefract(n, d):.
'''Reduces fractions. n is the numerator and d the denominator. '''.
def gcd(n, d):.
while d != ... .
t = d..