nit: Added link to `CONTRIBUTING.md` from the README
[nit.git] / lib / core / math.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2004-2008 Jean Privat <jean@pryen.org>
4 #
5 # This file is free software, which comes along with NIT. This software is
6 # distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
7 # without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
8 # PARTICULAR PURPOSE. You can modify it is you want, provided this header
9 # is kept unaltered, and a notification of the changes is added.
10 # You are allowed to redistribute it and sell it, alone or is a part of
11 # another product.
12
13 # Mathematical operations
14 module math is ldflags "-lm"
15
16 import kernel
17 import collection
18
19 in "C header" `{
20 #include <stdlib.h>
21 #include <math.h>
22 #include <time.h>
23 `}
24
25 in "C" `{
26 /* Is rand shortcut? */
27 static int nit_rand_seeded;
28 /* Current rand seed if seeded */
29 static unsigned int nit_rand_seed;
30
31 #define NIT_RAND_MAX 0x7fffffff
32
33 /* This algorithm is mentioned in the ISO C standard, here extended
34 for 32 bits. */
35 static int
36 nit_rand(void) {
37 unsigned int next = nit_rand_seed;
38 int result;
39
40 next *= 1103515245;
41 next += 12345;
42 result = (unsigned int) (next / 65536) % 2048;
43
44 next *= 1103515245;
45 next += 12345;
46 result <<= 10;
47 result ^= (unsigned int) (next / 65536) % 1024;
48
49 next *= 1103515245;
50 next += 12345;
51 result <<= 10;
52 result ^= (unsigned int) (next / 65536) % 1024;
53
54 nit_rand_seed = next;
55
56 return result;
57 }
58 `}
59
60 redef class Int
61 # Returns a random `Int` in `[0 .. self[`.
62 fun rand: Int `{
63 if (nit_rand_seeded) return (long)(((double)self)*nit_rand()/(NIT_RAND_MAX+1.0));
64 return (long)(((double)self)*rand()/(RAND_MAX+1.0));
65 `}
66
67 # Returns the result of a binary AND operation on `self` and `i`
68 #
69 # assert 0x10 & 0x01 == 0
70 fun &(i: Int): Int is intern `{ return self & i; `}
71
72 # Returns the result of a binary OR operation on `self` and `i`
73 #
74 # assert 0x10 | 0x01 == 0x11
75 fun |(i: Int): Int is intern `{ return self | i; `}
76
77 # Returns the result of a binary XOR operation on `self` and `i`
78 #
79 # assert 0x101 ^ 0x110 == 0x11
80 fun ^(i: Int): Int `{ return self ^ i; `}
81
82 # Returns the 1's complement of `self`
83 #
84 # assert ~0x2F == -48
85 fun ~: Int `{ return ~self; `}
86
87 # Returns the square root of `self`
88 #
89 # assert 16.sqrt == 4
90 fun sqrt: Int `{ return sqrt(self); `}
91
92 # Returns the greatest common divisor of `self` and `o`
93 #
94 # assert 54.gcd(24) == 6
95 # assert -54.gcd(-24) == 6
96 # assert 54.gcd(-24) == -6
97 # assert -54.gcd(24) == -6
98 # assert 12.gcd(6) == 6
99 fun gcd(o: Int): Int
100 do
101 if self < 0 then return -(-self).gcd(o)
102 if o < 0 then return -(self.gcd(-o))
103 if self == 0 or o == self then return o
104 if o == 0 then return self
105 if self & 1 == 0 then
106 if o & 1 == 1 then
107 return (self >> 1).gcd(o)
108 else
109 return (self >> 1).gcd(o >> 1) << 1
110 end
111 end
112 if o & 1 == 0 then return self.gcd(o >> 1)
113 if self > o then return ((self - o) >> 1).gcd(o)
114 return ((o - self) >> 1).gcd(self)
115 end
116
117 # Is `self` even ?
118 #
119 # assert 12.is_even
120 fun is_even: Bool do return self % 2 == 0
121
122 # Is `self` odd ?
123 #
124 # assert not 13.is_even
125 fun is_odd: Bool do return not is_even
126
127 # Is self a prime number ?
128 #
129 # assert 3.is_prime
130 # assert not 1.is_prime
131 # assert not 15.is_prime
132 fun is_prime: Bool
133 do
134 if self == 2 then
135 return true
136 else if self <= 1 or self.is_even then
137 return false
138 end
139 for i in [3..self.sqrt] do
140 if self % i == 0 then return false
141 end
142 return true
143 end
144
145 # Returns the `self` raised to the power of `e`.
146 #
147 # assert 2 ** 3 == 8
148 fun **(e: Int): Int
149 do
150 return self.to_f.pow(e.to_f).to_i
151 end
152
153 # The factorial of `self` (aka `self!`)
154 #
155 # Returns `1 * 2 * 3 * ... * self-1 * self`
156 #
157 # assert 0.factorial == 1 # by convention for an empty product
158 # assert 1.factorial == 1
159 # assert 4.factorial == 24
160 # assert 9.factorial == 362880
161 fun factorial: Int
162 do
163 assert self >= 0
164 var res = 1
165 var n = self
166 while n > 0 do
167 res = res * n
168 n -= 1
169 end
170 return res
171 end
172 end
173
174 redef class Byte
175 # Returns the result of a binary AND operation on `self` and `i`
176 #
177 # assert 0x10u8 & 0x01u8 == 0u8
178 fun &(i: Byte): Byte is intern `{ return self & i; `}
179
180 # Returns the result of a binary OR operation on `self` and `i`
181 #
182 # assert 0x10u8 | 0x01u8 == 0x11u8
183 fun |(i: Byte): Byte `{ return self | i; `}
184
185 # Returns the result of a binary XOR operation on `self` and `i`
186 #
187 # assert 0x101u8 ^ 0x110u8 == 0x11u8
188 fun ^(i: Byte): Byte `{ return self ^ i; `}
189
190 # Returns the 1's complement of `self`
191 #
192 # assert ~0x2Fu8 == 0xD0u8
193 fun ~: Byte `{ return ~self; `}
194 end
195
196 redef class Float
197
198 # Returns the non-negative square root of `self`.
199 #
200 # assert 9.0.sqrt == 3.0
201 # #assert 3.0.sqrt == 1.732
202 # assert 1.0.sqrt == 1.0
203 # assert 0.0.sqrt == 0.0
204 fun sqrt: Float `{ return sqrt(self); `}
205
206 # Computes the cosine of `self` (expressed in radians).
207 #
208 # #assert pi.cos == -1.0
209 fun cos: Float `{ return cos(self); `}
210
211 # Computes the sine of `self` (expressed in radians).
212 #
213 # #assert pi.sin == 0.0
214 fun sin: Float `{ return sin(self); `}
215
216 # Computes the cosine of x (expressed in radians).
217 #
218 # #assert 0.0.tan == 0.0
219 fun tan: Float `{ return tan(self); `}
220
221 # Computes the arc cosine of `self`.
222 #
223 # #assert 0.0.acos == pi / 2.0
224 fun acos: Float `{ return acos(self); `}
225
226 # Computes the arc sine of `self`.
227 #
228 # #assert 1.0.asin == pi / 2.0
229 fun asin: Float `{ return asin(self); `}
230
231 # Computes the arc tangent of `self`.
232 #
233 # #assert 0.0.tan == 0.0
234 fun atan: Float `{ return atan(self); `}
235
236 # Returns the absolute value of `self`.
237 #
238 # assert 12.0.abs == 12.0
239 # assert (-34.56).abs == 34.56
240 # assert -34.56.abs == -34.56
241 fun abs: Float `{ return fabs(self); `}
242
243 # Returns `self` raised at `e` power.
244 #
245 # #assert 2.0.pow(0.0) == 1.0
246 # #assert 2.0.pow(3.0) == 8.0
247 # #assert 0.0.pow(9.0) == 0.0
248 fun pow(e: Float): Float `{ return pow(self, e); `}
249
250 # Natural logarithm of `self`.
251 #
252 # assert 0.0.log.is_inf == -1
253 # #assert 1.0.log == 0.0
254 fun log: Float `{ return log(self); `}
255
256 # Logarithm of `self` to base `base`.
257 #
258 # assert 100.0.log_base(10.0) == 2.0
259 # assert 256.0.log_base(2.0) == 8.0
260 fun log_base(base: Float): Float do return log/base.log
261
262 # Returns *e* raised to `self`.
263 fun exp: Float `{ return exp(self); `}
264
265 # assert 1.1.ceil == 2.0
266 # assert 1.9.ceil == 2.0
267 # assert 2.0.ceil == 2.0
268 # assert (-1.5).ceil == -1.0
269 fun ceil: Float `{ return ceil(self); `}
270
271 # assert 1.1.floor == 1.0
272 # assert 1.9.floor == 1.0
273 # assert 2.0.floor == 2.0
274 # assert (-1.5).floor == -2.0
275 fun floor: Float `{ return floor(self); `}
276
277 # Rounds the value of a float to its nearest integer value
278 #
279 # assert 1.67.round == 2.0
280 # assert 1.34.round == 1.0
281 # assert -1.34.round == -1.0
282 # assert -1.67.round == -2.0
283 fun round: Float `{ return round(self); `}
284
285 # Returns a random `Float` in `[0.0 .. self[`.
286 fun rand: Float `{
287 if (nit_rand_seeded) return ((self)*nit_rand())/(NIT_RAND_MAX+1.0);
288 return ((self)*rand())/(RAND_MAX+1.0);
289 `}
290
291 # Returns the euclidean distance from `b`.
292 fun hypot_with(b: Float): Float `{ return hypotf(self, b); `}
293
294 # Returns true is self is not a number.
295 #
296 # As `nan != nan`, `is_nan` should be used to test if a float is the special *not a number* value.
297 #
298 # ~~~
299 # assert nan != nan # By IEEE 754
300 # assert nan.is_nan
301 # assert not 10.0.is_nan
302 # ~~~
303 fun is_nan: Bool `{ return isnan(self); `}
304
305 # Is the float an infinite value
306 # this function returns:
307 #
308 # * 1 if self is positive infinity
309 # * -1 if self is negative infinity
310 # * 0 otherwise
311 #
312 # ~~~
313 # assert 10.0.is_inf == 0
314 # assert inf.is_inf == 1
315 # assert (-inf).is_inf == -1
316 # ~~~
317 fun is_inf: Int do
318 if native_is_inf then
319 if self < 0.0 then return -1
320 return 1
321 end
322 return 0
323 end
324
325 private fun native_is_inf: Bool `{ return isinf(self); `}
326
327 # Linear interpolation between `a` and `b` using `self` as weight
328 #
329 # ~~~
330 # assert 0.0.lerp(0.0, 128.0) == 0.0
331 # assert 0.5.lerp(0.0, 128.0) == 64.0
332 # assert 1.0.lerp(0.0, 128.0) == 128.0
333 # assert -0.5.lerp(0.0, 128.0) == -64.0
334 # ~~~
335 fun lerp(a, b: Float): Float do return (1.0 - self) * a + self * b
336
337 # Quadratic Bézier interpolation between `a` and `b` with an `handle` using `self` as weight
338 #
339 # ~~~
340 # assert 0.00.qerp(0.0, 32.0, 128.0) == 0.0
341 # assert 0.25.qerp(0.0, 32.0, 128.0) == 20.0
342 # assert 0.50.qerp(0.0, 32.0, 128.0) == 48.0
343 # assert 0.75.qerp(0.0, 32.0, 128.0) == 84.0
344 # assert 1.00.qerp(0.0, 32.0, 128.0) == 128.0
345 # ~~~
346 fun qerp(a, handle, b: Float): Float do
347 var p = self
348 var i = 1.0 - p
349 var r = i*i * a +
350 2.0*i*p * handle +
351 p*p * b
352 return r
353 end
354
355 # Cubic Bézier interpolation between `a` and `b` with two handles using `self` as weight
356 #
357 # The Cubic Bézier interpolation is the most common one and use two control points.
358 #
359 # ~~~
360 # assert 0.00.cerp(0.0, 32.0, 128.0, 64.0) == 0.0
361 # assert 0.25.cerp(0.0, 32.0, 128.0, 64.0) == 32.5
362 # assert 0.50.cerp(0.0, 32.0, 128.0, 64.0) == 68.0
363 # assert 0.75.cerp(0.0, 32.0, 128.0, 64.0) == 85.5
364 # assert 1.00.cerp(0.0, 32.0, 128.0, 64.0) == 64.0
365 # ~~~
366 fun cerp(a, a_handle, b_handle, b: Float): Float do
367 var p = self
368 var i = 1.0 - p
369 var r = i*i*i * a +
370 3.0*i*i*p * a_handle +
371 3.0*i*p*p * b_handle +
372 p*p*p * b
373 return r
374 end
375 end
376
377 # Positive float infinite (IEEE 754)
378 #
379 # assert inf > 10.0
380 # assert inf.is_inf == 1
381 #
382 # `inf` follows the arithmetic of infinites
383 #
384 # assert (inf - 1.0) == inf
385 # assert (inf - inf).is_nan
386 #
387 # The negative infinite can be used as `-inf`.
388 #
389 # assert -inf < -10.0
390 # assert (-inf).is_inf == -1
391 fun inf: Float do return 1.0 / 0.0
392
393 # Not a Number, representation of an undefined or unrepresentable float (IEEE 754).
394 #
395 # `nan` is not comparable with itself, you should use `Float::is_nan` to test it.
396 #
397 # ~~~
398 # assert nan.is_nan
399 # assert nan != nan # By IEEE 754
400 # ~~~
401 #
402 # `nan` is the quiet result of some undefined operations.
403 #
404 # ~~~
405 # assert (1.0 + nan).is_nan
406 # assert (0.0 / 0.0).is_nan
407 # assert (inf - inf).is_nan
408 # assert (inf / inf).is_nan
409 # assert (-1.0).sqrt.is_nan
410 # ~~~
411 fun nan: Float do return 0.0 / 0.0
412
413 redef class Collection[ E ]
414 # Return a random element form the collection
415 # There must be at least one element in the collection
416 #
417 # ~~~
418 # var x = [1,2,3].rand
419 # assert x == 1 or x == 2 or x == 3
420 # ~~~
421 fun rand: E
422 do
423 if is_empty then abort
424 var rand_index = length.rand
425
426 for e in self do
427 if rand_index == 0 then return e
428 rand_index -= 1
429 end
430 abort
431 end
432
433 # Return a new array made of elements in a random order.
434 #
435 # ~~~
436 # var a = [1,2,1].to_shuffle
437 # assert a == [1,1,2] or a == [1,2,1] or a == [2,1,1]
438 # ~~~
439 fun to_shuffle: Array[E]
440 do
441 var res = self.to_a
442 res.shuffle
443 return res
444 end
445
446 # Return a new array made of (at most) `length` elements randomly chosen.
447 #
448 # ~~~
449 # var a = [1,2,1].sample(2)
450 # assert a == [1,1] or a == [1,2] or a == [2,1]
451 # ~~~
452 #
453 # If there is not enough elements, then the result only contains them in a random order.
454 # See `to_shuffle`.
455 #
456 # ENSURE `result.length == self.length.min(length)`
457 #
458 # Note: the default implementation uses the Reservoir Algorithm
459 fun sample(length: Int): Array[E]
460 do
461 if length >= self.length then return to_shuffle
462
463 var res = new Array[E].with_capacity(length)
464 var it = iterator
465 for i in [0..length[ do
466 res[i] = it.item
467 it.next
468 end
469 res.shuffle
470 for i in [length+1..self.length] do
471 var j = i.rand
472 if j < length then
473 res[j] = it.item
474 end
475 it.next
476 end
477 return res
478 end
479 end
480
481 redef class SequenceRead[E]
482 # Optimized for large collections using `[]`
483 redef fun rand
484 do
485 assert not is_empty
486 return self[length.rand]
487 end
488 end
489
490 redef class AbstractArray[E]
491 # Reorder randomly the elements in self.
492 #
493 # ~~~
494 # var a = new Array[Int]
495 #
496 # a.shuffle
497 # assert a.is_empty
498 #
499 # a.add 1
500 # a.shuffle
501 # assert a == [1]
502 #
503 # a.add 2
504 # a.shuffle
505 # assert a == [1,2] or a == [2,1]
506 # ~~~
507 #
508 # ENSURE self.shuffle.has_exactly(old(self))
509 fun shuffle
510 do
511 for i in [0..length[ do
512 var j = i + (length-i).rand
513 var tmp = self[i]
514 self[i] = self[j]
515 self[j] = tmp
516 end
517 end
518 end
519
520 redef class Sys
521 init
522 do
523 srand
524 end
525 end
526
527 # Computes the arc tangent given `y` and `x`.
528 #
529 # assert atan2(-0.0, 1.0) == -0.0
530 # assert atan2(0.0, 1.0) == 0.0
531 fun atan2(y: Float, x: Float): Float `{ return atan2(y, x); `}
532
533 # Approximate value of **pi**.
534 fun pi: Float do return 3.14159265
535
536 # Initialize the pseudo-random generator with the given seed.
537 # The pseudo-random generator is used by the method `rand` and other to generate sequence of numbers.
538 # These sequences are repeatable by calling `srand_from` with a same seed value.
539 #
540 # ~~~~
541 # srand_from(0)
542 # var a = 10.rand
543 # var b = 100.rand
544 # srand_from(0)
545 # assert 10.rand == a
546 # assert 100.rand == b
547 # ~~~~
548 fun srand_from(x: Int) `{ nit_rand_seeded = 1; nit_rand_seed = (unsigned int)x; `}
549
550 # Reinitialize the pseudo-random generator used by the method `rand` and other.
551 # This method is automatically invoked at the begin of the program, so usually, there is no need to manually invoke it.
552 # The only exception is in conjunction with `srand_from` to reset the pseudo-random generator.
553 fun srand `{ nit_rand_seeded = 0; srand((unsigned int)time(NULL)); `}