Merge: Added contributing guidelines and link from 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
173 # Is `self` a power of two ?
174 #
175 # ~~~nit
176 # assert not 3.is_pow2
177 # assert 2.is_pow2
178 # assert 1.is_pow2
179 # assert not 0.is_pow2
180 # ~~~
181 fun is_pow2: Bool do return self != 0 and (self & self - 1) == 0
182 end
183
184 redef class Byte
185 # Returns the result of a binary AND operation on `self` and `i`
186 #
187 # assert 0x10u8 & 0x01u8 == 0u8
188 fun &(i: Byte): Byte is intern `{ return self & i; `}
189
190 # Returns the result of a binary OR operation on `self` and `i`
191 #
192 # assert 0x10u8 | 0x01u8 == 0x11u8
193 fun |(i: Byte): Byte `{ return self | i; `}
194
195 # Returns the result of a binary XOR operation on `self` and `i`
196 #
197 # assert 0x101u8 ^ 0x110u8 == 0x11u8
198 fun ^(i: Byte): Byte `{ return self ^ i; `}
199
200 # Returns the 1's complement of `self`
201 #
202 # assert ~0x2Fu8 == 0xD0u8
203 fun ~: Byte `{ return ~self; `}
204 end
205
206 redef class Float
207
208 # Returns the non-negative square root of `self`.
209 #
210 # assert 9.0.sqrt == 3.0
211 # #assert 3.0.sqrt == 1.732
212 # assert 1.0.sqrt == 1.0
213 # assert 0.0.sqrt == 0.0
214 fun sqrt: Float `{ return sqrt(self); `}
215
216 # Computes the cosine of `self` (expressed in radians).
217 #
218 # #assert pi.cos == -1.0
219 fun cos: Float `{ return cos(self); `}
220
221 # Computes the sine of `self` (expressed in radians).
222 #
223 # #assert pi.sin == 0.0
224 fun sin: Float `{ return sin(self); `}
225
226 # Computes the cosine of x (expressed in radians).
227 #
228 # #assert 0.0.tan == 0.0
229 fun tan: Float `{ return tan(self); `}
230
231 # Computes the arc cosine of `self`.
232 #
233 # #assert 0.0.acos == pi / 2.0
234 fun acos: Float `{ return acos(self); `}
235
236 # Computes the arc sine of `self`.
237 #
238 # #assert 1.0.asin == pi / 2.0
239 fun asin: Float `{ return asin(self); `}
240
241 # Computes the arc tangent of `self`.
242 #
243 # #assert 0.0.tan == 0.0
244 fun atan: Float `{ return atan(self); `}
245
246 # Returns the absolute value of `self`.
247 #
248 # assert 12.0.abs == 12.0
249 # assert (-34.56).abs == 34.56
250 # assert -34.56.abs == -34.56
251 fun abs: Float `{ return fabs(self); `}
252
253 # Returns `self` raised at `e` power.
254 #
255 # #assert 2.0.pow(0.0) == 1.0
256 # #assert 2.0.pow(3.0) == 8.0
257 # #assert 0.0.pow(9.0) == 0.0
258 fun pow(e: Float): Float `{ return pow(self, e); `}
259
260 # Natural logarithm of `self`.
261 #
262 # assert 0.0.log.is_inf == -1
263 # #assert 1.0.log == 0.0
264 fun log: Float `{ return log(self); `}
265
266 # Logarithm of `self` to base `base`.
267 #
268 # assert 100.0.log_base(10.0) == 2.0
269 # assert 256.0.log_base(2.0) == 8.0
270 fun log_base(base: Float): Float do return log/base.log
271
272 # Returns *e* raised to `self`.
273 fun exp: Float `{ return exp(self); `}
274
275 # assert 1.1.ceil == 2.0
276 # assert 1.9.ceil == 2.0
277 # assert 2.0.ceil == 2.0
278 # assert (-1.5).ceil == -1.0
279 fun ceil: Float `{ return ceil(self); `}
280
281 # assert 1.1.floor == 1.0
282 # assert 1.9.floor == 1.0
283 # assert 2.0.floor == 2.0
284 # assert (-1.5).floor == -2.0
285 fun floor: Float `{ return floor(self); `}
286
287 # Rounds the value of a float to its nearest integer value
288 #
289 # assert 1.67.round == 2.0
290 # assert 1.34.round == 1.0
291 # assert -1.34.round == -1.0
292 # assert -1.67.round == -2.0
293 fun round: Float `{ return round(self); `}
294
295 # Returns a random `Float` in `[0.0 .. self[`.
296 fun rand: Float `{
297 if (nit_rand_seeded) return ((self)*nit_rand())/(NIT_RAND_MAX+1.0);
298 return ((self)*rand())/(RAND_MAX+1.0);
299 `}
300
301 # Returns the euclidean distance from `b`.
302 fun hypot_with(b: Float): Float `{ return hypotf(self, b); `}
303
304 # Returns true is self is not a number.
305 #
306 # As `nan != nan`, `is_nan` should be used to test if a float is the special *not a number* value.
307 #
308 # ~~~
309 # assert nan != nan # By IEEE 754
310 # assert nan.is_nan
311 # assert not 10.0.is_nan
312 # ~~~
313 fun is_nan: Bool `{ return isnan(self); `}
314
315 # Is the float an infinite value
316 # this function returns:
317 #
318 # * 1 if self is positive infinity
319 # * -1 if self is negative infinity
320 # * 0 otherwise
321 #
322 # ~~~
323 # assert 10.0.is_inf == 0
324 # assert inf.is_inf == 1
325 # assert (-inf).is_inf == -1
326 # ~~~
327 fun is_inf: Int do
328 if native_is_inf then
329 if self < 0.0 then return -1
330 return 1
331 end
332 return 0
333 end
334
335 private fun native_is_inf: Bool `{ return isinf(self); `}
336
337 # Linear interpolation between `a` and `b` using `self` as weight
338 #
339 # ~~~
340 # assert 0.0.lerp(0.0, 128.0) == 0.0
341 # assert 0.5.lerp(0.0, 128.0) == 64.0
342 # assert 1.0.lerp(0.0, 128.0) == 128.0
343 # assert -0.5.lerp(0.0, 128.0) == -64.0
344 # ~~~
345 fun lerp(a, b: Float): Float do return (1.0 - self) * a + self * b
346
347 # Quadratic Bézier interpolation between `a` and `b` with an `handle` using `self` as weight
348 #
349 # ~~~
350 # assert 0.00.qerp(0.0, 32.0, 128.0) == 0.0
351 # assert 0.25.qerp(0.0, 32.0, 128.0) == 20.0
352 # assert 0.50.qerp(0.0, 32.0, 128.0) == 48.0
353 # assert 0.75.qerp(0.0, 32.0, 128.0) == 84.0
354 # assert 1.00.qerp(0.0, 32.0, 128.0) == 128.0
355 # ~~~
356 fun qerp(a, handle, b: Float): Float do
357 var p = self
358 var i = 1.0 - p
359 var r = i*i * a +
360 2.0*i*p * handle +
361 p*p * b
362 return r
363 end
364
365 # Cubic Bézier interpolation between `a` and `b` with two handles using `self` as weight
366 #
367 # The Cubic Bézier interpolation is the most common one and use two control points.
368 #
369 # ~~~
370 # assert 0.00.cerp(0.0, 32.0, 128.0, 64.0) == 0.0
371 # assert 0.25.cerp(0.0, 32.0, 128.0, 64.0) == 32.5
372 # assert 0.50.cerp(0.0, 32.0, 128.0, 64.0) == 68.0
373 # assert 0.75.cerp(0.0, 32.0, 128.0, 64.0) == 85.5
374 # assert 1.00.cerp(0.0, 32.0, 128.0, 64.0) == 64.0
375 # ~~~
376 fun cerp(a, a_handle, b_handle, b: Float): Float do
377 var p = self
378 var i = 1.0 - p
379 var r = i*i*i * a +
380 3.0*i*i*p * a_handle +
381 3.0*i*p*p * b_handle +
382 p*p*p * b
383 return r
384 end
385 end
386
387 # Positive float infinite (IEEE 754)
388 #
389 # assert inf > 10.0
390 # assert inf.is_inf == 1
391 #
392 # `inf` follows the arithmetic of infinites
393 #
394 # assert (inf - 1.0) == inf
395 # assert (inf - inf).is_nan
396 #
397 # The negative infinite can be used as `-inf`.
398 #
399 # assert -inf < -10.0
400 # assert (-inf).is_inf == -1
401 fun inf: Float do return 1.0 / 0.0
402
403 # Not a Number, representation of an undefined or unrepresentable float (IEEE 754).
404 #
405 # `nan` is not comparable with itself, you should use `Float::is_nan` to test it.
406 #
407 # ~~~
408 # assert nan.is_nan
409 # assert nan != nan # By IEEE 754
410 # ~~~
411 #
412 # `nan` is the quiet result of some undefined operations.
413 #
414 # ~~~
415 # assert (1.0 + nan).is_nan
416 # assert (0.0 / 0.0).is_nan
417 # assert (inf - inf).is_nan
418 # assert (inf / inf).is_nan
419 # assert (-1.0).sqrt.is_nan
420 # ~~~
421 fun nan: Float do return 0.0 / 0.0
422
423 redef class Collection[ E ]
424 # Return a random element form the collection
425 # There must be at least one element in the collection
426 #
427 # ~~~
428 # var x = [1,2,3].rand
429 # assert x == 1 or x == 2 or x == 3
430 # ~~~
431 fun rand: E
432 do
433 if is_empty then abort
434 var rand_index = length.rand
435
436 for e in self do
437 if rand_index == 0 then return e
438 rand_index -= 1
439 end
440 abort
441 end
442
443 # Return a new array made of elements in a random order.
444 #
445 # ~~~
446 # var a = [1,2,1].to_shuffle
447 # assert a == [1,1,2] or a == [1,2,1] or a == [2,1,1]
448 # ~~~
449 fun to_shuffle: Array[E]
450 do
451 var res = self.to_a
452 res.shuffle
453 return res
454 end
455
456 # Return a new array made of (at most) `length` elements randomly chosen.
457 #
458 # ~~~
459 # var a = [1,2,1].sample(2)
460 # assert a == [1,1] or a == [1,2] or a == [2,1]
461 # ~~~
462 #
463 # If there is not enough elements, then the result only contains them in a random order.
464 # See `to_shuffle`.
465 #
466 # ENSURE `result.length == self.length.min(length)`
467 #
468 # Note: the default implementation uses the Reservoir Algorithm
469 fun sample(length: Int): Array[E]
470 do
471 if length >= self.length then return to_shuffle
472
473 var res = new Array[E].with_capacity(length)
474 var it = iterator
475 for i in [0..length[ do
476 res[i] = it.item
477 it.next
478 end
479 res.shuffle
480 for i in [length+1..self.length] do
481 var j = i.rand
482 if j < length then
483 res[j] = it.item
484 end
485 it.next
486 end
487 return res
488 end
489 end
490
491 redef class SequenceRead[E]
492 # Optimized for large collections using `[]`
493 redef fun rand
494 do
495 assert not is_empty
496 return self[length.rand]
497 end
498 end
499
500 redef class AbstractArray[E]
501 # Reorder randomly the elements in self.
502 #
503 # ~~~
504 # var a = new Array[Int]
505 #
506 # a.shuffle
507 # assert a.is_empty
508 #
509 # a.add 1
510 # a.shuffle
511 # assert a == [1]
512 #
513 # a.add 2
514 # a.shuffle
515 # assert a == [1,2] or a == [2,1]
516 # ~~~
517 #
518 # ENSURE self.shuffle.has_exactly(old(self))
519 fun shuffle
520 do
521 for i in [0..length[ do
522 var j = i + (length-i).rand
523 var tmp = self[i]
524 self[i] = self[j]
525 self[j] = tmp
526 end
527 end
528 end
529
530 redef class Sys
531 init
532 do
533 srand
534 end
535 end
536
537 # Computes the arc tangent given `y` and `x`.
538 #
539 # assert atan2(-0.0, 1.0) == -0.0
540 # assert atan2(0.0, 1.0) == 0.0
541 fun atan2(y: Float, x: Float): Float `{ return atan2(y, x); `}
542
543 # Approximate value of **pi**.
544 fun pi: Float do return 3.14159265
545
546 # Initialize the pseudo-random generator with the given seed.
547 # The pseudo-random generator is used by the method `rand` and other to generate sequence of numbers.
548 # These sequences are repeatable by calling `srand_from` with a same seed value.
549 #
550 # ~~~~
551 # srand_from(0)
552 # var a = 10.rand
553 # var b = 100.rand
554 # srand_from(0)
555 # assert 10.rand == a
556 # assert 100.rand == b
557 # ~~~~
558 fun srand_from(x: Int) `{ nit_rand_seeded = 1; nit_rand_seed = (unsigned int)x; `}
559
560 # Reinitialize the pseudo-random generator used by the method `rand` and other.
561 # This method is automatically invoked at the begin of the program, so usually, there is no need to manually invoke it.
562 # The only exception is in conjunction with `srand_from` to reset the pseudo-random generator.
563 fun srand `{ nit_rand_seeded = 0; srand((unsigned int)time(NULL)); `}