usingMaths.com
From Theory to Practice - Math You Can Use.







<< Previous Next >>

Multiplying Fractions with Python: A Step-by-Step Tutorial



Understanding the Math Behind Fraction Multiplication | Maths Explanation for Python Kids

Learning how to multiply fractions in Python is a great way to combine math skills with coding. This tutorial is designed for junior secondary students who want to understand fraction multiplication using simple Python classes and constructors.

Multiplying fractions is pretty straightforward:
Cancel out all common factors between numerators and denominators, then multiply whatever is left numerator to numerator and denominator to denominator.

In this lesson, we'll walk through the step-by-step method of multiplying fractions using Python. You'll learn how to define a class, use constructors, and apply logic to find mutual factors and simplify results.


Step-by-Step Explanation of Algorithm to Multiply Fractions in Python

This Python algorithm for fractions shows how to multiply two fractions and reduce them to their lowest terms. It's a great math coding project for beginners.
Understanding how to multiply multiple fractions in Python helps students build both computational thinking and math fluency. It's a foundational skill for more advanced topics like algebra and data science.

If we have
                  4/9 x 21/8;

Step 1:

Find any common factor between any numerator and any denominator.

Step 2:

Cancel out any such common factor.

= X7
421
98
3 
Step 3:

Repeat Steps 1 & 2 recursively until there are no more common factors.

=1X 
47
38
 2
=7
6

Create a new Python module file; call it MultiplyFraction.py. Type out the adjoining Python code for multiplying fractions.


Note: You can comment out the LowestTerm Python object code in the main class from the previous lesson or simply continue from where it stopped.


So! Python Fun Practice Exercise - Multiply Fractions

As a fun practice exercise, feel free to try out your own fractions with different numerators and denominators, and see how the Python code multiplies those fractions.







Python Code for Multiplying Fractions - Module File

# A class
class TimesFraction:

    # Simulate a constructor
    def __init__(self, fractions):
        self.numerators   = fractions['numerators']
        self.denominators = fractions['denominators']

        self.trial_factor = 0
        self.n_index = 0
        self.d_index = 0
        self.answer = [1, 1]

        # set trial_factor to the highest value amongst
        #both numerators and denominators
        for numerator in self.numerators:
            if numerator > self.trial_factor:
                self.trial_factor = numerator
        for denominator in self.denominators:
            if denominator > self.trial_factor:
                self.trial_factor = denominator

    # Returns a dictionary of the new numerator and denominator
    def doMultiply(self):
        # STEP 3:
        # We are counting down to test for mutual factors 
        while self.trial_factor > 1:
            # STEP 1:
            # iterate through numerators and check for factors
            while self.n_index < len(self.numerators):
                self.mutual_factor = False
                if self.numerators[self.n_index] % self.trial_factor == 0: # do we have a factor
                    # iterate through denominators and check for factors
                    while self.d_index < len(self.denominators):
                        if self.denominators[self.d_index] % self.trial_factor == 0: # is this factor mutual?
                            self.mutual_factor = True
                            break # stop as soon as we find a mutual factor so preserve the corresponding index

                        self.d_index += 1

                    break # stop as soon as we find a mutual factor so as to preserve the corresponding index

                self.n_index += 1

            # STEP 2:
            # where we have a mutual factor
            if self.mutual_factor:
                self.numerators[self.n_index]   /= self.trial_factor
                self.denominators[self.d_index] /= self.trial_factor
                continue continue with next iteration repeating the current value of trial_factor

            self.n_index = 0
            self.d_index = 0
            self.trial_factor -= 1


        for numerator in self.numerators:
            self.answer[0] *= numerator
        for denominator in self.denominators:
            self.answer[1] *= denominator
            
        return {'numerator':int(self.answer[0]), 'denominator':int(self.answer[1])}

Python Code for Multiplying Fractions - Main Class

#!/usr/bin/python
from MultiplyFraction import TimesFraction

##
 # Multiplying fractions
 ##
numerators   = [16, 20, 27, 20]
denominators = [9, 9, 640, 7]
fractions = {'numerators':numerators, 'denominators':denominators}

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

# use the MultiplyFraction class
mul_fract = TimesFraction(fractions)
fraction = mul_fract.doMultiply()

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


print('\n\n')




<< Previous Next >>