-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrational-number.ts
375 lines (291 loc) · 10.2 KB
/
rational-number.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
import greatestCommonDivisor from './gcd'
import integerNthRoot from './integer-nth-root'
export interface RationalNumberLike<T extends (number | string | bigint) = (number | string | bigint)> {
readonly numerator: T;
readonly denominator: T;
}
function isRationalNumberLike(value: unknown): value is RationalNumberLike {
if (typeof value !== 'undefined' && value !== null) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const typeofNumerator = typeof (value as any).numerator
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const typeofDenominator = typeof (value as any).denominator
return (
typeofDenominator === 'string'
|| typeofDenominator === 'number'
|| typeofDenominator === 'bigint'
)
&& (
typeofNumerator === 'string'
|| typeofNumerator === 'number'
|| typeofNumerator === 'bigint'
)
}
return false
}
type ParsableValue = number | string | bigint | RationalNumberLike | [number | string | bigint, number | string | bigint]
function normalizeValue({ numerator, denominator }: RationalNumberLike<bigint>): RationalNumberLike<bigint> {
if (denominator === BigInt(0)) {
throw new RangeError(`Division by zero`)
}
if (denominator < BigInt(0)) {
numerator *= BigInt(-1)
denominator *= BigInt(-1)
}
return {
numerator,
denominator,
}
}
function parseValue(value: ParsableValue): RationalNumberLike<bigint> {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
if (value instanceof RationalNumber) {
return value
}
let numerator: bigint
let denominator: bigint
if (Array.isArray(value)) {
numerator = BigInt(value[0])
denominator = BigInt(value[1])
} else if (isRationalNumberLike(value)) {
numerator = BigInt(value.numerator)
denominator = BigInt(value.denominator)
} else if (typeof value === 'bigint' || (typeof value === 'number' && Number.isInteger(value))) {
numerator = BigInt(value)
denominator = BigInt(1)
} else {
value = `${value}`
const isNegative = value.startsWith('-')
if (isNegative || value.startsWith('+')) {
value = value.substr(1)
}
const [decimal = '', fraction = ''] = value.split('.')
const fractionDigits = fraction.length
denominator = BigInt(`1${'0'.repeat(fractionDigits)}`)
numerator = ((BigInt(decimal) * denominator) + BigInt(fraction)) * BigInt(isNegative ? -1 : 1)
}
return normalizeValue({
numerator,
denominator,
})
}
function stringify(value: RationalNumberLike<bigint>, precision: number): string {
value = normalizeValue(value)
let numerator = value.numerator
const denominator = value.denominator
const isNegative = numerator < BigInt(0)
if (isNegative) {
numerator *= BigInt(-1)
}
const decimal = (numerator / denominator)
let denominatorFraction = (numerator % denominator) * BigInt(10)
let fraction = ''
while (denominatorFraction !== BigInt(0) && fraction.length < precision) {
const tmp = denominatorFraction / denominator
if (tmp > BigInt(0)) {
denominatorFraction = (denominatorFraction % denominator) * BigInt(10)
} else {
denominatorFraction *= BigInt(10)
}
fraction += tmp.toString()
}
return `${isNegative ? '-' : ''}${decimal}${fraction.length > 0 ? `.${fraction}` : ''}`
}
const values = new WeakMap<RationalNumber, { numerator: bigint; denominator: bigint }>()
function getValueBag(key: RationalNumber): { numerator: bigint; denominator: bigint } {
if (values.has(key)) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return values.get(key)!
}
const value = { numerator: BigInt(0), denominator: BigInt(1) }
values.set(key, value)
return value
}
/**
* ```
* NUMERATOR
* ---
* DENOMINATOR
* ```
*/
export default class RationalNumber implements RationalNumberLike<bigint> {
constructor(value: ParsableValue) {
const bag = getValueBag(this);
const { numerator, denominator } = parseValue(value)
const gcd = greatestCommonDivisor(numerator, denominator)
bag.numerator = numerator / gcd
bag.denominator = denominator / gcd
}
public get numerator(): bigint {
return getValueBag(this).numerator
}
public get denominator(): bigint {
return getValueBag(this).denominator
}
public valueOf(): number {
return Number(stringify(this, 16))
}
public toString(): string {
return stringify(this, 16)
}
public toFixed(precision: number): string {
return stringify(this, precision)
}
/**
* re-creates `RationalNumber` instance from previously serialized value
*/
public static fromJSON(value: string): RationalNumber {
const [numerator, denominator] = value.split('/')
return new this({ numerator, denominator })
}
/**
* serialize value to JSON, this method is meant to be used indirectly by `JSON.serialize`
*/
public toJSON(): string {
const { numerator, denominator } = getValueBag(this)
return `${numerator}/${denominator}`
}
public add(value: ParsableValue): RationalNumber {
const { denominator: aDenominator, numerator: aNumerator } = parseValue(value)
if (aNumerator === BigInt(0)) {
return this
}
const { denominator: bDenominator, numerator: bNumerator } = getValueBag(this)
const denominator = aDenominator * bDenominator
const numerator = (aNumerator * (denominator / aDenominator)) + (bNumerator * (denominator / bDenominator))
return new RationalNumber({
denominator,
numerator,
})
}
public substract(value: ParsableValue): RationalNumber {
const { numerator, denominator } = parseValue(value)
return this.add({
numerator: numerator * BigInt(-1),
denominator,
})
}
public inverse(): RationalNumber {
const { numerator, denominator } = getValueBag(this)
return new RationalNumber({
numerator: denominator,
denominator: numerator,
})
}
public multiply(value: ParsableValue): RationalNumber {
const { denominator: aDenominator, numerator: aNumerator } = parseValue(value)
const { denominator: bDenominator, numerator: bNumerator } = getValueBag(this)
const denominator = aDenominator * bDenominator
const numerator = aNumerator * bNumerator
return new RationalNumber({
denominator,
numerator,
})
}
public divide(value: ParsableValue): RationalNumber {
const { numerator, denominator } = parseValue(value)
return this.multiply({
numerator: denominator,
denominator: numerator,
})
}
public int(): RationalNumber {
const {
numerator,
denominator,
} = getValueBag(this)
return new RationalNumber(numerator / denominator)
}
public mod(value: ParsableValue): RationalNumber {
const modulator = value instanceof RationalNumber ? value : new RationalNumber(value)
return this.substract(
modulator.multiply(
this.divide(modulator).int(),
),
)
}
public abs(): RationalNumber {
const { numerator, denominator } = getValueBag(this)
if (numerator < BigInt(0)) {
return new RationalNumber({ numerator: -numerator, denominator })
}
return this
}
public power(exponent: ParsableValue, precision = BigInt(16)): RationalNumber {
const rationalExponent = parseValue(exponent)
// x ** 0
if (rationalExponent.numerator === BigInt(0)) {
return new RationalNumber(1)
}
// x ** 1
if (rationalExponent.numerator === rationalExponent.denominator) {
return this
}
// x ** n, where n < 0
if (rationalExponent.numerator < BigInt(0)) {
return this.inverse().power({
numerator: -rationalExponent.numerator,
denominator: rationalExponent.denominator,
})
}
const numerator = this.numerator ** rationalExponent.numerator
const denominator = this.denominator ** rationalExponent.numerator
const result = new RationalNumber({ numerator, denominator })
// exponent is not an integer
if (rationalExponent.denominator !== BigInt(1)) {
return result.root(rationalExponent.denominator, precision)
}
return result
}
/**
* @see https://en.wikipedia.org/wiki/Nth_root_algorithm
*/
public root(degree: string | number | bigint, precision = BigInt(16)): RationalNumber {
// root(x, n), where x < 0
if (this.numerator < BigInt(0)) {
throw new RangeError('rooting not allowed on negative numbers')
}
degree = typeof degree === 'bigint' ? degree : BigInt(degree)
// root(x, n), where n <= 0
if (degree <= BigInt(0)) {
throw new RangeError('root degree has to be greater than 0')
}
// root(0, n)
if (this.numerator === BigInt(0)) {
return this
}
// root(x, 1)
if (degree === BigInt(1)) {
return this
}
let current: RationalNumber = this.divide(degree)
/**
* it's a shortcut for calculating roots of integers,
* in some cases (eg. `root(9, 3)`) the standard approach may never be finished nor return the correct result,
* because the Newton-Rhapson method uses calculus which means in each iteration it is only getting closer to the actual result which may be never reached,
* in the example above (`root(9, 3)`) obviously equals `3`,
* but when using rational numbers instead of integers the result is not achieved in a rational amount of iterations
*
* when `denominator === 1` the number is an integer
*/
if (this.denominator === BigInt(1)) {
current = new RationalNumber(integerNthRoot(this.numerator, degree))
// validation
if (current.numerator ** degree === this.numerator) {
return current
}
} else {
current = this.divide(degree)
}
let iteration = BigInt(0)
let previous: RationalNumber
const multiper = new RationalNumber({ numerator: 1, denominator: degree })
const degreeMinusOne = new RationalNumber(degree - BigInt(1))
do {
previous = current
current = multiper.multiply(previous.multiply(degreeMinusOne).add(this.divide(previous.power(degreeMinusOne))))
iteration++
} while (iteration < precision && !(previous.numerator === current.numerator && previous.denominator === current.denominator))
return current
}
}