From d3ebe8e5fb01015d27b5076a1430b872c779c6b0 Mon Sep 17 00:00:00 2001 From: Akash Saravanan Date: Fri, 16 Oct 2020 23:48:19 +0530 Subject: [PATCH] Add intersection of two lines. --- mathgenerator/mathgen.py | 56 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/mathgenerator/mathgen.py b/mathgenerator/mathgen.py index bd22657..a85d7c3 100644 --- a/mathgenerator/mathgen.py +++ b/mathgenerator/mathgen.py @@ -1,4 +1,5 @@ import random +import fractions genList = [] @@ -464,6 +465,60 @@ def commonFactorsFunc(maxVal=100): problem = f"Common Factors of {a} and {b} = " solution = arr return problem, solution + +def intersectionOfTwoLinesFunc( + minM=-10, maxM=10, minB=-10, maxB=10, minDenominator=1, maxDenominator=6 +): + def generateEquationString(m, b): + """ + Generates an equation given the slope and intercept. + It handles cases where m is fractional. + It also ensures that we don't have weird signs such as y = mx + -b. + """ + if m[1] == 1: + m = m[0] + else: + m = f"{m[0]}/{m[1]}" + base = f"y = {m}x" + if b > 0: + return f"{base} + {b}" + elif b < 0: + return f"{base} - {b * -1}" + else: + return base + + def fractionToString(x): + """ + Converts the given fractions.Fraction into a string. + """ + if x.denominator == 1: + x = x.numerator + else: + x = f"{x.numerator}/{x.denominator}" + return x + + m1 = (random.randint(minM, maxM), random.randint(minDenominator, maxDenominator)) + m2 = (random.randint(minM, maxM), random.randint(minDenominator, maxDenominator)) + b1 = random.randint(minB, maxB) + b2 = random.randint(minB, maxB) + equation1 = generateEquationString(m1, b1) + equation2 = generateEquationString(m2, b2) + problem = "Find the point of intersection of the two lines: " + problem += f"{equation1} and {equation2}" + m1 = fractions.Fraction(*m1) + m2 = fractions.Fraction(*m2) + # if m1 == m2 then the slopes are equal + # This can happen if both line are the same + # Or if they are parallel + # In either case there is no intersection + if m1 == m2: + solution = "No Solution" + else: + intersection_x = (b1 - b2) / (m2 - m1) + intersection_y = ((m2 * b1) - (m1 * b2)) / (m2 - m1) + solution = f"({fractionToString(intersection_x)}, {fractionToString(intersection_y)})" + return problem, solution + # || Class Instances #Format is: @@ -502,3 +557,4 @@ angleRegularPolygon = Generator("Angle of a Regular Polygon",29,"Find the angle combinations = Generator("Combinations of Objects",30, "Combinations available for picking 4 objects at a time from 6 distinct objects ="," 15", combinationsFunc) factorial = Generator("Factorial", 31, "a! = ", "b", factorialFunc) commonFactors = Generator("Common Factors", 32, "Common Factors of {a} and {b} = ","[c, d, ...]",commonFactorsFunc) +intersectionOfTwoLines = Generator("Intersection of Two Lines", 33, "Find the point of intersection of the two lines: y = m1*x + b1 and y = m2*x + b2", "(x, y)", intersectionOfTwoLinesFunc)