### Install Fraction.js Source: https://context7.com/rawify/fraction.js/llms.txt Use npm to install the library in your project. ```bash npm install fraction.js ``` -------------------------------- ### Build Fraction.js Library Source: https://github.com/rawify/fraction.js/blob/main/README.md After cloning the repository, install dependencies and run the build script to compile the library. ```bash npm install npm run build ``` -------------------------------- ### Install Fraction.js via yarn Source: https://github.com/rawify/fraction.js/blob/main/README.md Use yarn to add Fraction.js to your project dependencies. ```bash yarn add fraction.js ``` -------------------------------- ### Complex Fraction Arithmetic Example Source: https://github.com/rawify/fraction.js/blob/main/README.md Performs a sequence of arithmetic operations including multiplication and modulo with fractions, demonstrating handling of repeating decimals. ```javascript var f = new Fraction("9.4'31'"); // 9.4313131313131... f.mul([-4, 3]).mod("4.'8'"); // 4.88888888888888... ``` -------------------------------- ### Method: toFraction Source: https://github.com/rawify/fraction.js/blob/main/README.md Gets a string representation of the fraction. ```APIDOC ## toFraction([showMixed]) ### Description Gets a string representation of the fraction. ### Parameters #### Query Parameters - **showMixed** (boolean) - Optional - If true, displays as a mixed fraction (e.g., '1 1/3' instead of '4/3'). Defaults to false. ``` -------------------------------- ### Method: toContinued Source: https://github.com/rawify/fraction.js/blob/main/README.md Gets an array of the fraction represented as a continued fraction. ```APIDOC ## toContinued() ### Description Gets an array of the fraction represented as a continued fraction. The first element always contains the whole part. ### Response - **Array** - An array of numbers representing the continued fraction. ``` -------------------------------- ### Get Exact Fractional Part of a Number with Fraction.js Source: https://github.com/rawify/fraction.js/blob/main/README.md Extract the exact fractional part of a number, including repeating decimals, by using the mod(1) and abs() methods. ```javascript var f = new Fraction("-6.(3416)"); console.log(f.mod(1).abs().toFraction()); // = 3416/9999 ``` -------------------------------- ### Convert Fraction to Continued Fraction Array Source: https://github.com/rawify/fraction.js/blob/main/README.md Use the toContinued() method to get an array representation of a fraction as a continued fraction. The first element is the whole part. ```javascript var f = new Fraction('88/33'); var c = f.toContinued(); // [2, 1, 2] ``` -------------------------------- ### Run Fraction.js Tests Source: https://github.com/rawify/fraction.js/blob/main/README.md Execute the test suite to verify the integrity of the Fraction.js library. ```bash npm run test ``` -------------------------------- ### Include in Browser Source: https://context7.com/rawify/fraction.js/llms.txt Load the library directly in a browser environment via script tag. ```html ``` -------------------------------- ### Import Fraction.js Source: https://context7.com/rawify/fraction.js/llms.txt Load the library using CommonJS or ES Modules. ```javascript // CommonJS const Fraction = require('fraction.js'); // ES Modules import Fraction from 'fraction.js'; ``` -------------------------------- ### Clone Fraction.js Repository Source: https://github.com/rawify/fraction.js/blob/main/README.md Download the Fraction.js source code directly from its GitHub repository. ```bash git clone https://github.com/rawify/Fraction.js ``` -------------------------------- ### Create Fraction Objects Source: https://context7.com/rawify/fraction.js/llms.txt Initialize fractions from various data types including numbers, strings, arrays, objects, and BigInts. ```javascript const Fraction = require('fraction.js'); // From integers const a = new Fraction(123); console.log(a.toString()); // "123" // From decimals (uses Farey Sequences for approximation) const b = new Fraction(0.5); console.log(b.toFraction()); // "1/2" // From two arguments (numerator, denominator) const c = new Fraction(3, 4); console.log(c.toFraction()); // "3/4" // From string fractions const d = new Fraction("123/456"); console.log(d.toFraction()); // "41/152" // From colon notation const e = new Fraction("8128371:12394"); console.log(e.toString()); // Same as "8128371/12394" // From mixed fractions const f = new Fraction("4 1/2"); console.log(f.valueOf()); // 4.5 // From arrays [numerator, denominator] const g = new Fraction([22, 7]); console.log(g.toString()); // "3.(142857)" // From objects {n: numerator, d: denominator} const h = new Fraction({ n: 1, d: 3 }); console.log(h.toString()); // "0.(3)" // From BigInt values const i = new Fraction(1n, 3n); console.log(i.toString()); // "0.(3)" ``` -------------------------------- ### Import Fraction.js in Node.js (CommonJS) Source: https://github.com/rawify/fraction.js/blob/main/README.md Use require to import the Fraction.js library in a Node.js environment. ```javascript const Fraction = require('fraction.js'); ``` -------------------------------- ### Parse Integers into Fractions with Fraction.js Source: https://github.com/rawify/fraction.js/blob/main/README.md Create a Fraction.js object directly from an integer value. ```javascript new Fraction(123); ``` -------------------------------- ### Create Fractions from Numerator and Denominator Source: https://github.com/rawify/fraction.js/blob/main/README.md Instantiate a Fraction.js object by providing the numerator and denominator as separate arguments. ```javascript new Fraction(3, 2); // 3/2 = 1.5 ``` -------------------------------- ### Compare fractions with fraction.js Source: https://context7.com/rawify/fraction.js/llms.txt Check equality, ordering, and divisibility of rational numbers. ```javascript const Fraction = require('fraction.js'); // Equality check const a = new Fraction([98, 5]).equals("-19.6"); console.log(a); // false const b = new Fraction([-98, 5]).equals("-19.6"); console.log(b); // true // Less than const c = new Fraction(1).lt(2); console.log(c); // true // Less than or equal const d = new Fraction(2).lte(2); console.log(d); // true // Greater than const e = new Fraction(3).gt(2); console.log(e); // true // Greater than or equal const f = new Fraction(2).gte(2); console.log(f); // true // Compare (returns -1, 0, or 1) const g = new Fraction(3.5).compare(4.1); console.log(g); // -1 (3.5 < 4.1) const h = new Fraction(4.3).compare(4.3); console.log(h); // 0 (equal) const i = new Fraction(4.1).compare(3.5); console.log(i); // 1 (4.1 > 3.5) // Divisibility check const j = new Fraction(100.5).divisible(1.5); console.log(j); // true const k = new Fraction([2, 3]).divisible([1, 6]); console.log(k); // true (because (2/3) / (1/6) = 4) ``` -------------------------------- ### Import Fraction.js in Node.js (ES Modules) Source: https://github.com/rawify/fraction.js/blob/main/README.md Use import to bring the Fraction.js library into your Node.js project when using ES Modules. ```javascript import Fraction from 'fraction.js'; ``` -------------------------------- ### Include Fraction.js in HTML Source: https://github.com/rawify/fraction.js/blob/main/README.md Add the fraction.min.js script to your HTML file to use Fraction.js in the browser. ```html ``` -------------------------------- ### Parse Numbers into Fractions using Arrays or Objects Source: https://github.com/rawify/fraction.js/blob/main/README.md Instantiate Fraction.js objects using arrays for numerator/denominator or objects with 'n' and 'd' properties. ```javascript new Fraction(numerator, denominator); new Fraction([numerator, denominator]); new Fraction({n: numerator, d: denominator}); ``` -------------------------------- ### Calculate powers and logarithms with fraction.js Source: https://context7.com/rawify/fraction.js/llms.txt Perform rational powers and logarithms. Returns null if the result is irrational. ```javascript const Fraction = require('fraction.js'); // Integer powers const a = new Fraction(2, 3).pow(7); console.log(a.toFraction()); // "128/2187" // Negative powers const b = new Fraction(-0.5).pow(-3); console.log(b.valueOf()); // -8 // Rational powers (returns fraction if result is rational) const c = new Fraction(27).pow("2/3"); console.log(c.valueOf()); // 9 (because 27^(2/3) = 9) const d = new Fraction("243/1024").pow("2/5"); console.log(d.valueOf()); // 0.5625 // Returns null for irrational results const e = new Fraction(2).pow(0.5); console.log(e); // null (sqrt(2) is irrational) // Logarithms const f = new Fraction(8).log(2); console.log(f.valueOf()); // 3 (because 2^3 = 8) const g = new Fraction(81).log(27); console.log(g.toString()); // "1.(3)" (because 27^(4/3) = 81) const h = new Fraction("27/8").log("9/4"); console.log(h.valueOf()); // 1.5 (because (9/4)^(3/2) = 27/8) // Returns null for non-rational logarithms const i = new Fraction(3).log(2); console.log(i); // null ``` -------------------------------- ### Compare rational numbers Source: https://github.com/rawify/fraction.js/blob/main/README.md Explains the return values for the compare method when evaluating two rational numbers. ```text result < 0: n is greater than actual number result > 0: n is smaller than actual number result = 0: n is equal to the actual number ``` -------------------------------- ### Handling Repeating Decimals Source: https://github.com/rawify/fraction.js/blob/main/README.md Demonstrates how Fraction.js can handle repeating decimal places and provides a utility function to format decimal strings for repeating patterns. ```APIDOC ## Handling Repeating Decimals *Fraction.js* can easily handle repeating decimal places. For example *1/3* is *0.3333...*. There is only one repeating digit. As you can see in the examples above, you can pass a number like *1/3* as "0.'3'" or "0.(3)", which are synonym. There are no tests to parse something like 0.166666666 to 1/6! If you really want to handle this number, wrap around brackets on your own with the function below for example: 0.1(66666666) Assume you want to divide 123.32 / 33.6(567). [WolframAlpha](http://www.wolframalpha.com/input/?i=123.32+%2F+%2812453%2F370%29) states that you'll get a period of 1776 digits. *Fraction.js* comes to the same result. Give it a try: ```javascript var f = new Fraction("123.32"); console.log("Bam: " + f.div("33.6(567)")); ``` To automatically make a number like "0.123123123" to something more Fraction.js friendly like "0.(123)", I hacked this little brute force algorithm in a 10 minutes. Improvements are welcome... ```javascript function formatDecimal(str) { var comma, pre, offset, pad, times, repeat; if (-1 === (comma = str.indexOf("."))) return str; pre = str.substr(0, comma + 1); str = str.substr(comma + 1); for (var i = 0; i < str.length; i++) { offset = str.substr(0, i); for (var j = 0; j < 5; j++) { pad = str.substr(i, j + 1); times = Math.ceil((str.length - offset.length) / pad.length); repeat = new Array(times + 1).join(pad); // Silly String.repeat hack if (0 === (offset + repeat).indexOf(str)) { return pre + offset + "(" + pad + ")"; } } } return null; } var f, x = formatDecimal("13.0123123123"); // = 13.0(123) if (x !== null) { f = new Fraction(x); } ``` ``` -------------------------------- ### Use Utility Methods for Fraction Manipulation Source: https://context7.com/rawify/fraction.js/llms.txt Perform common operations such as absolute value, negation, inversion, cloning, and simplification with error tolerance. ```javascript const Fraction = require('fraction.js'); // Absolute value const a = new Fraction(-100.25).abs(); console.log(a.valueOf()); // 100.25 const b = new Fraction("-6.(3416)").mod(1).abs(); console.log(b.toFraction()); // "3416/9999" // Negation const c = new Fraction("1/3").neg(); console.log(c.toString()); // "-0.(3)" const d = new Fraction(-4).neg(); console.log(d.valueOf()); // 4 // Inverse (reciprocal) const e = new Fraction("2/7").inverse(); console.log(e.valueOf()); // 3.5 const f = new Fraction([-3, 4]).inverse(); console.log(f.toString()); // "-1.(3)" // Clone const original = new Fraction("123.'3'"); const copy = original.clone(); console.log(copy.toFraction()); // "370/3" // Simplify with error tolerance const g = new Fraction(0.333).simplify(0.001); console.log(g.toFraction()); // "1/3" const h = new Fraction(415, 93).simplify(0.1); console.log(h.toFraction()); // "9/2" const i = new Fraction(415, 93).simplify(0.01); console.log(i.toFraction()); // "58/13" ``` -------------------------------- ### Correct Calculation with Fraction.js Source: https://github.com/rawify/fraction.js/blob/main/README.md Shows how Fraction.js maintains precision for calculations that are inaccurate with standard floats. ```javascript Fraction(1).div(98).mul(98) // Returns 1 ``` -------------------------------- ### Method: clone Source: https://github.com/rawify/fraction.js/blob/main/README.md Creates a copy of the actual Fraction object. ```APIDOC ## clone() ### Description Creates a copy of the actual Fraction object. ### Response - **Fraction** - A new Fraction object instance. ``` -------------------------------- ### Parse Doubles into Fractions with Fraction.js Source: https://github.com/rawify/fraction.js/blob/main/README.md Instantiate Fraction.js objects from floating-point numbers. Note: For performance, consider passing numbers as strings or arrays if precision is critical. ```javascript new Fraction(55.4); ``` -------------------------------- ### Format decimal strings for Fraction.js Source: https://github.com/rawify/fraction.js/blob/main/README.md A brute-force utility function to convert standard repeating decimal strings into the bracketed format required by Fraction.js. ```javascript function formatDecimal(str) { var comma, pre, offset, pad, times, repeat; if (-1 === (comma = str.indexOf("."))) return str; pre = str.substr(0, comma + 1); str = str.substr(comma + 1); for (var i = 0; i < str.length; i++) { offset = str.substr(0, i); for (var j = 0; j < 5; j++) { pad = str.substr(i, j + 1); times = Math.ceil((str.length - offset.length) / pad.length); repeat = new Array(times + 1).join(pad); // Silly String.repeat hack if (0 === (offset + repeat).indexOf(str)) { return pre + offset + "(" + pad + ")"; } } } return null; } var f, x = formatDecimal("13.0123123123"); // = 13.0(123) if (x !== null) { f = new Fraction(x); } ``` -------------------------------- ### Approximate Irrational Numbers with Fraction.js Source: https://github.com/rawify/fraction.js/blob/main/README.md Use this algorithm to approximate irrational numbers like sqrt(5) - 2 by iteratively refining a fraction. The binary representation is also generated. ```javascript var x = "/", s = ""; var a = new Fraction(0), b = new Fraction(1); for (var n = 0; n <= 10; n++) { var c = a.add(b).div(2); console.log(n + "\t" + a + "\t" + b + "\t" + c + "\t" + x); if (c.add(2).pow(2).valueOf() < 5) { a = c; x = "1"; } else { b = c; x = "0"; } s+= x; } console.log(s) ``` -------------------------------- ### Method: toLatex Source: https://github.com/rawify/fraction.js/blob/main/README.md Generates an exact LaTeX representation of the fraction object. ```APIDOC ## toLatex([showMixed]) ### Description Generates an exact LaTeX representation of the actual object. ### Parameters #### Query Parameters - **showMixed** (boolean) - Optional - If true, displays as a mixed fraction (e.g., '1 1/3' instead of '4/3'). Defaults to false. ``` -------------------------------- ### Access Fraction attributes Source: https://github.com/rawify/fraction.js/blob/main/README.md Shows how to retrieve the numerator, denominator, and sign components of a Fraction object. ```javascript var f = new Fraction('-1/2'); console.log(f.n); // Numerator: 1 console.log(f.d); // Denominator: 2 console.log(f.s); // Sign: -1 ``` -------------------------------- ### Display Fraction as String Source: https://github.com/rawify/fraction.js/blob/main/README.md Converts a Fraction object to its string representation, showing the numerator and denominator. ```javascript console.log(f.toFraction()); // -4154 / 1485 ``` -------------------------------- ### Mathematical Functions Source: https://github.com/rawify/fraction.js/blob/main/README.md Lists and describes the various mathematical functions available in Fraction.js for performing operations on rational numbers. ```APIDOC ## Functions ### Fraction abs() Returns the actual number without any sign information ### Fraction neg() Returns the actual number with flipped sign in order to get the additive inverse ### Fraction add(n) Returns the sum of the actual number and the parameter n ### Fraction sub(n) Returns the difference of the actual number and the parameter n ### Fraction mul(n) Returns the product of the actual number and the parameter n ### Fraction div(n) Returns the quotient of the actual number and the parameter n ### Fraction pow(exp) Returns the power of the actual number, raised to an possible rational exponent. If the result becomes non-rational the function returns `null`. ### Fraction log(base) Returns the logarithm of the actual number to a given rational base. If the result becomes non-rational the function returns `null`. ### Fraction mod(n) Returns the modulus (rest of the division) of the actual object and n (this % n). It's a much more precise [fmod()](#fmod-impreciseness-circumvented) if you like. Please note that *mod()* is just like the modulo operator of most programming languages. If you want a mathematical correct modulo, see [here](#mathematical-correct-modulo). ### Fraction mod() Returns the modulus (rest of the division) of the actual object (numerator mod denominator) ### Fraction gcd(n) Returns the fractional greatest common divisor ### Fraction lcm(n) Returns the fractional least common multiple ### Fraction ceil([places=0-16]) Returns the ceiling of a rational number with Math.ceil ### Fraction floor([places=0-16]) Returns the floor of a rational number with Math.floor ### Fraction round([places=0-16]) Returns the rational number rounded with Math.round ### Fraction roundTo(multiple) Rounds a fraction to the closest multiple of another fraction. ### Fraction inverse() Returns the multiplicative inverse of the actual number (n / d becomes d / n) in order to get the reciprocal ### Fraction simplify([eps=0.001]) Simplifies the rational number under a certain error threshold. Ex. `0.333` will be `1/3` with `eps=0.001` ### boolean equals(n) Check if two rational numbers are equal ### boolean lt(n) Check if this rational number is less than another ### boolean lte(n) Check if this rational number is less than or equal another ### boolean gt(n) Check if this rational number is greater than another ### boolean gte(n) Check if this rational number is greater than or equal another ### int compare(n) Compare two numbers. ``` result < 0: n is greater than actual number result > 0: n is smaller than actual number result = 0: n is equal to the actual number ``` ### boolean divisible(n) Check if two numbers are divisible (n divides this) ### double valueOf() Returns a decimal representation of the fraction ``` -------------------------------- ### Demonstrate Floating-Point Inaccuracy Source: https://github.com/rawify/fraction.js/blob/main/README.md Illustrates the inaccuracies that can arise from standard floating-point arithmetic in JavaScript. ```javascript 1 / 98 * 98 // Results in 0.9999999999999999 ``` -------------------------------- ### Method: toString Source: https://github.com/rawify/fraction.js/blob/main/README.md Generates an exact string representation of the fraction object. ```APIDOC ## toString([decimalPlaces]) ### Description Generates an exact string representation of the given object. For repeating decimal places, digits within repeating cycles are enclosed in parentheses. For other numbers, the string will include up to the specified decimalPlaces significant digits. ### Parameters #### Query Parameters - **decimalPlaces** (number) - Optional - The number of significant digits to include. Defaults to 15. ``` -------------------------------- ### Convert Fractions to Output Formats Source: https://context7.com/rawify/fraction.js/llms.txt Transform fraction objects into decimal strings, LaTeX, continued fractions, or access internal BigInt attributes. ```javascript const Fraction = require('fraction.js'); const f = new Fraction("123.'3'"); // valueOf() - decimal number console.log(f.valueOf()); // 123.33333333333333 // toString() - decimal string with repeating notation console.log(f.toString()); // "123.(3)" // toString with decimal places limit const g = new Fraction(".0000000000000003"); console.log(g.toString(15)); // "0.000000000000000" console.log(g.toString(16)); // "0.0000000000000003" // toFraction() - fraction string console.log(f.toFraction()); // "370/3" console.log(f.toFraction(true)); // "123 1/3" (mixed fraction) // toLatex() - LaTeX representation console.log(f.toLatex()); // "\\frac{370}{3}" console.log(f.toLatex(true)); // "123\\frac{1}{3}" (mixed) // toContinued() - continued fraction array const h = new Fraction(415, 93); console.log(h.toContinued()); // [4n, 2n, 6n, 7n] const i = new Fraction("7/8"); console.log(i.toContinued()); // [0n, 1n, 7n] // Accessing internal attributes (BigInt values) const j = new Fraction("-1/2"); console.log(j.s); // -1n (sign) console.log(j.n); // 1n (numerator) console.log(j.d); // 2n (denominator) ``` -------------------------------- ### Handle Division by Zero Errors in Fraction.js Source: https://context7.com/rawify/fraction.js/llms.txt Use try-catch blocks to catch 'Division by Zero' errors when dividing by zero, either directly or through invalid fraction strings. ```javascript const Fraction = require('fraction.js'); // Division by zero try { const a = new Fraction(10).div(0); } catch (e) { console.log(e.message); // "Division by Zero" } try { const b = new Fraction("9/0"); } catch (e) { console.log(e.message); // "Division by Zero" } ``` -------------------------------- ### Mathematical Modulo Operation with Fraction.js Source: https://github.com/rawify/fraction.js/blob/main/README.md Achieve mathematically correct modulo results by adding the divisor and taking the modulo again, circumventing typical fmod() imprecision. ```javascript var a = -1; var b = 10.99; console.log(new Fraction(a) .mod(b)); // Not correct, usual Modulo console.log(new Fraction(a) .mod(b).add(b).mod(b)); // Correct! Mathematical Modulo ``` -------------------------------- ### Round fractions with fraction.js Source: https://context7.com/rawify/fraction.js/llms.txt Round rational numbers to integers, specific decimal places, or multiples of other fractions. ```javascript const Fraction = require('fraction.js'); // Ceil (round up) const a = new Fraction(0.4).ceil(); console.log(a.valueOf()); // 1 const b = new Fraction(-0.6).ceil(); console.log(b.valueOf()); // 0 // Ceil with decimal places const c = new Fraction(0.23).ceil(2); console.log(c.valueOf()); // 0.23 // Floor (round down) const d = new Fraction(0.6).floor(); console.log(d.valueOf()); // 0 const e = new Fraction(-0.4).floor(); console.log(e.valueOf()); // -1 // Floor with decimal places const f = new Fraction(10.4).floor(1); console.log(f.valueOf()); // 10.4 // Round (half away from zero) const g = new Fraction(10.5).round(); console.log(g.valueOf()); // 11 const h = new Fraction(-10.5).round(); console.log(h.valueOf()); // -10 // Round with decimal places const i = new Fraction(10.543).round(3); console.log(i.valueOf()); // 10.543 // Round to multiple of another fraction const j = new Fraction(0.9).roundTo("1/8"); console.log(j.toFraction()); // "7/8" const k = new Fraction("1/3").roundTo("1/16"); console.log(k.valueOf()); // 0.3125 const l = new Fraction("10/3").roundTo("1/2"); console.log(l.valueOf()); // 3.5 ``` -------------------------------- ### Floating-Point vs. Fraction.js Accuracy Comparison Source: https://github.com/rawify/fraction.js/blob/main/README.md Compares the result of a calculation using floating-point arithmetic versus Fraction.js, highlighting the precision difference. ```javascript (9.4313131 * (-4 / 3)) % 4.888888 = -2.797308133... ``` -------------------------------- ### Perform Probability Calculations Source: https://context7.com/rawify/fraction.js/llms.txt Represent probabilities as fractions to maintain precision during calculations. ```javascript const Fraction = require('fraction.js'); // P({3}) - probability of rolling a 3 on a fair die const p1 = new Fraction(1, 6); console.log(p1.toString()); // "0.1(6)" // P({1, 4}) - probability of rolling 1 or 4 const p2 = new Fraction(2, 6); console.log(p2.toString()); // "0.(3)" // P({2, 4, 6}) - probability of rolling even const p3 = new Fraction(3, 6); console.log(p3.toString()); // "0.5" ``` -------------------------------- ### Calculate Rational Approximation of Irrational Numbers Source: https://context7.com/rawify/fraction.js/llms.txt Use a bisection method with fraction objects to approximate irrational values like square roots. ```javascript const Fraction = require('fraction.js'); // Approximate sqrt(5) - 2 using bisection let a = new Fraction(0); let b = new Fraction(1); for (let n = 0; n <= 10; n++) { const c = a.add(b).div(2); if (c.add(2).pow(2).valueOf() < 5) { a = c; } else { b = c; } } console.log(a.toFraction()); // Approximation of sqrt(5) - 2 ``` -------------------------------- ### Calculate GCD and LCM with fraction.js Source: https://context7.com/rawify/fraction.js/llms.txt Perform greatest common divisor and least common multiple operations on integers and fractions. ```javascript const Fraction = require('fraction.js'); // GCD of integers const a = new Fraction(52).gcd(39); console.log(a.valueOf()); // 13 const b = new Fraction(51357).gcd(3819); console.log(b.valueOf()); // 57 // GCD of fractions: gcd(a/b, c/d) = gcd(a,c) / lcm(b,d) const c = new Fraction(5, 8).gcd([3, 7]); console.log(c.toFraction()); // "1/56" const d = new Fraction(2, 3).gcd([7, 5]); console.log(d.toFraction()); // "1/15" // LCM of integers const e = new Fraction(200).lcm(333); console.log(e.valueOf()); // 66600 // LCM with negative numbers const f = new Fraction(-3).lcm(3); console.log(f.valueOf()); // 3 // LCM with zero const g = new Fraction(0).lcm(3); console.log(g.valueOf()); // 0 ``` -------------------------------- ### Parse Strings into Fractions with Fraction.js Source: https://github.com/rawify/fraction.js/blob/main/README.md Fraction.js supports parsing various string formats, including decimals, fractions (with '/' or ':'), mixed numbers, and numbers with repeating decimals indicated by quotes or parentheses. ```javascript new Fraction("123.45"); new Fraction("123/45"); // A rational number represented as two decimals, separated by a slash new Fraction("123:45"); // A rational number represented as two decimals, separated by a colon new Fraction("4 123/45"); // A rational number represented as a whole number and a fraction new Fraction("123.'456'"); // Note the quotes, see below! new Fraction("123.(456)"); // Note the brackets, see below! new Fraction("123.45'6'"); // Note the quotes, see below! new Fraction("123.45(6)"); // Note the brackets, see below! ``` -------------------------------- ### Convert Degrees, Minutes, Seconds to Fraction Source: https://github.com/rawify/fraction.js/blob/main/README.md Converts a time-based angle (degrees, minutes, seconds) into a precise rational number representation using Fraction.js. ```javascript var deg = 57; // 57° var min = 45; // 45 Minutes var sec = 17; // 17 Seconds new Fraction(deg).add(min, 60).add(sec, 3600).toString() // -> 57.7547(2) ``` -------------------------------- ### Display Unicode Fractions Source: https://context7.com/rawify/fraction.js/llms.txt Map fraction objects to specific Unicode string representations using a lookup table. ```javascript const Fraction = require('fraction.js'); function toUnicodeFraction(frac) { const map = { '1:4': "1/4", '1:2': "1/2", '3:4': "3/4", '1:3': "1/3", '2:3': "2/3", '1:5': "1/5", '2:5': "2/5", '3:5': "3/5", '4:5': "4/5", '1:6': "1/6", '5:6': "5/6", '1:8': "1/8", '3:8': "3/8", '5:8': "5/8", '7:8': "7/8" }; return map[frac.n + ":" + frac.d] || frac.toFraction(false); } console.log(toUnicodeFraction(new Fraction(0.25))); // "1/4" ``` -------------------------------- ### Access Fraction Attributes Source: https://github.com/rawify/fraction.js/blob/main/README.md Demonstrates accessing the internal sign (s), numerator (n), and denominator (d) of a Fraction object. These attributes are stored as BigInt. ```javascript Number(f.s) * Number(f.n) / Number(f.d) = -1 * 4154 / 1485 = -2.797306... ``` -------------------------------- ### Handle Non-Integer Parameter Errors in Fraction.js Source: https://context7.com/rawify/fraction.js/llms.txt Catch 'Parameters must be integer' errors when using the two-argument constructor with non-integer values. ```javascript const Fraction = require('fraction.js'); // Non-integer parameters for two-argument constructor try { const e = new Fraction(12.5, 4); } catch (e) { console.log(e.message); // "Parameters must be integer" } ``` -------------------------------- ### Perform modulo operations with fraction.js Source: https://context7.com/rawify/fraction.js/llms.txt Execute precise modulo operations to avoid floating-point inaccuracies found in standard implementations. ```javascript const Fraction = require('fraction.js'); // Basic modulo const a = new Fraction(9).mod(2); console.log(a.valueOf()); // 1 // Precise fmod - solves floating-point issues // Standard JS: 4.55 % 0.05 = 0.04999999999999957 const b = new Fraction(4.55).mod(0.05); console.log(b.valueOf()); // 0 (correct answer) // Another fmod precision fix const c = new Fraction(1.0).mod(0.1); console.log(c.valueOf()); // 0 (not 0.09999999999999995) // Extract fractional part of a number const d = new Fraction("381.(33411)").mod(1); console.log(d.toString()); // "0.(33411)" // Modulo without argument returns n % d const e = new Fraction(20, 10).mod(); console.log(e.equals(0)); // true (is integer) // Complex modulo const f = new Fraction("381.(33411)").mod("11.119(356)"); console.log(f.toString()); // "3.275(997225017295217)" // Mathematical correct modulo (different from programming modulo) const x = new Fraction(-1).mod(10.99).add(10.99).mod(10.99); console.log(x.toString()); // Mathematical modulo result ``` -------------------------------- ### Divide numbers with repeating decimals Source: https://github.com/rawify/fraction.js/blob/main/README.md Demonstrates dividing two numbers where one contains a repeating decimal sequence defined by parentheses. ```javascript var f = new Fraction("123.32"); console.log("Bam: " + f.div("33.6(567)")); ``` -------------------------------- ### Convert Degrees, Minutes, and Seconds to Decimal Source: https://context7.com/rawify/fraction.js/llms.txt Use fraction arithmetic to convert sexagesimal time or angle units into a decimal representation. ```javascript const Fraction = require('fraction.js'); const deg = 57; // 57 degrees const min = 45; // 45 minutes const sec = 17; // 17 seconds // 57 + 45/60 + 17/3600 const result = new Fraction(deg).add(min, 60).add(sec, 3600); console.log(result.toString()); // "57.7547(2)" ``` -------------------------------- ### Attribute Access Source: https://github.com/rawify/fraction.js/blob/main/README.md Provides direct access to the numerator, denominator, and sign attributes of a Fraction object. ```APIDOC ## Attributes The Fraction object allows direct access to the numerator, denominator and sign attributes. It is ensured that only the sign-attribute holds sign information so that a sign comparison is only necessary against this attribute. ```javascript var f = new Fraction('-1/2'); console.log(f.n); // Numerator: 1 console.log(f.d); // Denominator: 2 console.log(f.s); // Sign: -1 ``` ``` -------------------------------- ### Simplify Fraction with Error Tolerance Source: https://github.com/rawify/fraction.js/blob/main/README.md Simplifies a fraction while allowing for a specified error tolerance. The result is returned as a string in its simplest form. ```javascript let x = new Fraction(0.33333); let res = x.simplify(0.001) // Error < 0.001 .toFraction(); // Returns "1/3" as a string ``` -------------------------------- ### Handle Invalid Argument Errors in Fraction.js Source: https://context7.com/rawify/fraction.js/llms.txt Catch 'Invalid argument' errors when providing non-numeric or improperly formatted strings to the Fraction constructor. This includes handling leading spaces. ```javascript const Fraction = require('fraction.js'); // Invalid parameter try { const c = new Fraction("foo"); } catch (e) { console.log(e.message); // "Invalid argument" } try { const d = new Fraction(" 123"); // Leading space } catch (e) { console.log(e.message); // "Invalid argument" } ``` -------------------------------- ### Perform Arithmetic Operations Source: https://context7.com/rawify/fraction.js/llms.txt Execute precise mathematical operations including addition, subtraction, multiplication, and division. ```javascript const Fraction = require('fraction.js'); // Addition const sum = new Fraction("1/2").add("1/3"); console.log(sum.toFraction()); // "5/6" console.log(sum.toString()); // "0.8(3)" // Subtraction const diff = new Fraction("3/4").sub("1/4"); console.log(diff.toFraction()); // "1/2" // Multiplication - solves precision issues const product = new Fraction(1).div(98).mul(98); console.log(product.valueOf()); // 1 (not 0.9999999999999999) // Division const quotient = new Fraction("10/15").div("3/4"); console.log(quotient.toString()); // "0.(8)" // Chained operations const result = new Fraction("9.4'31'") .mul([-4, 3]) .mod("4.'8'"); console.log(result.toFraction()); // "-4154/1485" // With different input formats const mixed = new Fraction("4/5") .add("13/2"); console.log(mixed.toString()); // "7.3" ``` -------------------------------- ### Convert Decimal to Fraction Source: https://github.com/rawify/fraction.js/blob/main/README.md Converts a decimal number to its precise fractional string representation. Use `toFraction(true)` for mixed number format. ```javascript let x = new Fraction(1.88); let res = x.toFraction(true); // Returns "1 22/25" as a string ``` -------------------------------- ### Handle Repeating Decimals Source: https://context7.com/rawify/fraction.js/llms.txt Parse repeating decimal strings using parentheses or quotes for exact representation. ```javascript const Fraction = require('fraction.js'); // Repeating decimals with parentheses const a = new Fraction("0.(3)"); // 0.333... console.log(a.toFraction()); // "1/3" // Repeating decimals with quotes const b = new Fraction("0.'142857'"); // 0.142857142857... console.log(b.toFraction()); // "1/7" // Partial repeating decimals const c = new Fraction("123.45(6)"); // 123.456666... console.log(c.toFraction()); // "11111/90" // Complex repeating pattern const d = new Fraction("9.4'31'"); // 9.4313131... console.log(d.toFraction()); // "9337/990" // Division resulting in repeating decimal const e = new Fraction("123.32").div("33.6(567)"); console.log(e.toString()); // Long repeating decimal with 1776 digit period ``` -------------------------------- ### Calculate Probability P({3}) Source: https://github.com/rawify/fraction.js/blob/main/README.md Calculates the probability of rolling a 3 on a fair six-sided die using Fraction.js. The result is a string representing the repeating decimal. ```javascript var p = new Fraction([3].length, 6).toString(); // "0.1(6)" ``` -------------------------------- ### Calculate Probability P({1, 4}) Source: https://github.com/rawify/fraction.js/blob/main/README.md Calculates the probability of rolling either a 1 or a 4 on a fair six-sided die. The result is a string representing the repeating decimal. ```javascript var p = new Fraction([1, 4].length, 6).toString(); // "0.(3)" ``` -------------------------------- ### Calculate Probability P({2, 4, 6}) Source: https://github.com/rawify/fraction.js/blob/main/README.md Calculates the probability of rolling an even number (2, 4, or 6) on a fair six-sided die. The result is a string representing the decimal. ```javascript var p = new Fraction([2, 4, 6].length, 6).toString(); // "0.5" ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.