Fractions are maintained by default in reduced form. For example, setting the value to 2/4 will automatically be reduced (simplified) to 1/2. However functions for forcing non-reduced fractions are provided, particularly for avoiding speed issues in intermediate calculations (although the current mathematical functions will reduce the fraction after every calculation to minimize the chance of overflow).
This implementation limits the numerator and denominator to the
range from 0 to 253–1 plus a sign, and optional
automatic overflow detection is included by running
CheckOverflowOff() turning this feature off.
This code can be installed globally for use in node with the command:
$ npm install -g rational-number
If you want to install locally within anode project, then install as a package dependency with the command:
$ npm install --save rational-number
Here is an code example which loads the module into a node script, creates two RationalNumbers (4/5 and 13/2), adds them, and then prints the result to the console:
var RationalNumber = require('rational-number'); var rn1 = new RationalNumber(4, 5); var rn2 = new RationalNumber('26/4'); var rn3 = rn1.add(rn2); console.log(rn1.toString(),"+",rn2.toString(),"=",rn3.toString()); console.log(rn1.toStringMixed("_"),"+",rn2.toStringMixed("_"), "=",rn3.toStringMixed("_")); console.log(rn1.valueOf()+" + "+rn2.valueOf()+" = "+rn3.valueOf());
The above code should output the following text to the console:
4/5 + 13/2 = 73/10 4/5 + 6_1/2 = 7_3/10 0.8 + 6.5 = 7.3
<script src="RationalNumber-base.js"></script> <script src="RationalNumber-math.js"></script>
Input and output from the RationalNumber code can be tested using
directory of the repository. To test from a node installation:
$ npm install # to download mocha dependency if necessary $ npm test
If you have mocha installed globally in your
search path (such as with "
npm install -g mocha"), you can also
type one of the following equivalent shell commands to run the code
$ make test $ mocha test $ cd test; make $ cd test; mocha
The following RationalNumber methods provide additional arithmetic processing from the optional RationalNumber-math.js file: