Finding Fractions and JavaScript
In mathematics, fraction sum refers to the process of adding two fractions, which is often also called fraction addition.
In JavaScript, we can use regular mathematical operators to perform the addition of two or more fractions. However, since the numerators and denominators of fractions are usually whole numbers, some special operations are required when performing addition of fractions.
Here are some useful JavaScript snippets to help you perform addition operations when working with fractions.
function addFractions(f1, f2) { const numerator = (f1.numerator * f2.denominator) + (f2.numerator * f1.denominator); const denominator = f1.denominator * f2.denominator; return { numerator, denominator }; }
Using this function, we can add two fractions and return the result as a new fraction.
const f1 = { numerator: 1, denominator: 2 }; const f2 = { numerator: 3, denominator: 4 }; const result = addFractions(f1, f2); console.log(result); // {numerator: 5, denominator: 4}
function addDecimalFractions(f1, f2) { const decimal1 = f1.numerator / f1.denominator; const decimal2 = f2.numerator / f2.denominator; const decimalSum = decimal1 + decimal2; return decimalSum; }
We can use this function to calculate the decimal value of the sum of two fractions.
const f1 = { numerator: 1, denominator: 2 }; const f2 = { numerator: 3, denominator: 4 }; const decimalSum = addDecimalFractions(f1, f2); console.log(decimalSum); // 1.25
function addFractionsWithLCM(f1, f2) { const lcm = (f1.denominator * f2.denominator) / gcd(f1.denominator, f2.denominator); const newNumerator1 = f1.numerator * (lcm / f1.denominator); const newNumerator2 = f2.numerator * (lcm / f2.denominator); const numerator = newNumerator1 + newNumerator2; const denominator = lcm; return { numerator, denominator }; } function gcd(a, b) { return b === 0 ? a : gcd(b, a % b); }
The above code snippet is used to add two fractions and return a new fraction object, universal fraction and reduced fraction.
const f1 = { numerator: 1, denominator: 2 }; const f2 = { numerator: 3, denominator: 4 }; const result = addFractionsWithLCM(f1, f2); console.log(result); // {numerator: 5, denominator: 4}
JavaScript has an extensive math library and functions that can be used to perform a variety of mathematical operations. When it comes to adding fractions, using one of the methods above allows us to do the calculations easily.
The above is the detailed content of Finding Fractions and JavaScript. For more information, please follow other related articles on the PHP Chinese website!