UNPKG

2.62 kBMarkdownView Raw
1# rationals
2_extended rational number type for javascript_
3
4Why I think this lib is great:
5
6- Representing fractions is not just easy, but it's natural. This is what
7rational numbers do best. Operations like `0.1 + 0.2` are a pain in js,
8but using rational numbers, it's just: `r(1,10).plus(1,5) === r(3,10)`
9
10- This lib provides a type of object which will work with 1/0 or 0/0 just as well.
11This is especially useful if you plan to plot values on a graph.
12
13I've got the inspiration for this lib from here: [MF105: The extended rational numbers in practice](http://www.youtube.com/watch?v=YMQkLojL2ek)
14
15# Support
16[![browser support](https://ci.testling.com/ashnur/rationals.png)](https://ci.testling.com/ashnur/rationals)
17
18
19
20
21# Examples
22```
23var r = require('rationals');
24
25r(1) === r(1); // true, denominator of 1 is optional
26
27r(1,1) === r(1); // true
28
29r(2,4) === r(13,26); // true, all rationals will be always reduced
30
31r(100,50) === r(2); // true
32
33r(1,2).plus(r(1,3)).minus(r(1,4)).times(r(1,5)).per(r(1,6)) === r(49,70); // true, chaining works
34
35r(355,113).val(); // 3.1415929203539825, my personal favorite aproximation of Pi, from ancient china
36
37
38```
39
40# API
41- _a & b are objects created with the rationals() function_
42( I deleted the internal checks for this, so you should make sure to construct the numbers yourself)
43- in the parentheses you have some common aliases for the functions
44
45
46#### Addition
47- add (plus)
48
49 `a.add(b)`
50
51#### Subtraction
52- subtract (minus, sub)
53
54 `a.sub(b)`
55
56#### Multiplication
57- multiply (times, mul)
58
59 `a.mul(b)`
60
61#### Division
62- divide (per, div)
63
64 `a.div(b)`
65
66#### Examining
67- toString
68
69 Examining an object can be hard, but if you cast it to a string: `r(355,113)+''` will return `'355/113'`.
70
71 So will `r(625/125).toString()` return `'5/1'`.
72
73#### Display
74- display
75
76 Just like toString(), but the numerator will be shown only if it's not 1. That is, integers will appear without a slash and a denominator.
77
78 `r(625/125).display()` returns `'5'`.
79
80#### Approximation
81- val
82
83 Will return the numerator divided with the denominator.
84
85 `r(355,113).val(); //3.1415929203539825`
86
87# Good to know
88If you provide anything else as the numerator, than a whole number in base 10 an exception will be thrown.
89On the other hand, if you do the same with the denominator, it will be cast to 1. This is because
90I am lazy, and I do not want to handle wrong values and undefined values differently throwing for the former
91and casting to 1 for the latter.
92
93# Install
94```
95npm install rationals
96```
97
98**You can use it in the browser with [browserify](http://browserify.org/)**