lmathlib.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  1. /*
  2. ** $Id: lmathlib.c,v 1.122 2018/03/09 15:05:13 roberto Exp roberto $
  3. ** Standard mathematical library
  4. ** See Copyright Notice in lua.h
  5. */
  6. #define lmathlib_c
  7. #define LUA_LIB
  8. #include "lprefix.h"
  9. #include <float.h>
  10. #include <limits.h>
  11. #include <math.h>
  12. #include <stdlib.h>
  13. #include "lua.h"
  14. #include "lauxlib.h"
  15. #include "lualib.h"
  16. #undef PI
  17. #define PI (l_mathop(3.141592653589793238462643383279502884))
  18. static int math_abs (lua_State *L) {
  19. if (lua_isinteger(L, 1)) {
  20. lua_Integer n = lua_tointeger(L, 1);
  21. if (n < 0) n = (lua_Integer)(0u - (lua_Unsigned)n);
  22. lua_pushinteger(L, n);
  23. }
  24. else
  25. lua_pushnumber(L, l_mathop(fabs)(luaL_checknumber(L, 1)));
  26. return 1;
  27. }
  28. static int math_sin (lua_State *L) {
  29. lua_pushnumber(L, l_mathop(sin)(luaL_checknumber(L, 1)));
  30. return 1;
  31. }
  32. static int math_cos (lua_State *L) {
  33. lua_pushnumber(L, l_mathop(cos)(luaL_checknumber(L, 1)));
  34. return 1;
  35. }
  36. static int math_tan (lua_State *L) {
  37. lua_pushnumber(L, l_mathop(tan)(luaL_checknumber(L, 1)));
  38. return 1;
  39. }
  40. static int math_asin (lua_State *L) {
  41. lua_pushnumber(L, l_mathop(asin)(luaL_checknumber(L, 1)));
  42. return 1;
  43. }
  44. static int math_acos (lua_State *L) {
  45. lua_pushnumber(L, l_mathop(acos)(luaL_checknumber(L, 1)));
  46. return 1;
  47. }
  48. static int math_atan (lua_State *L) {
  49. lua_Number y = luaL_checknumber(L, 1);
  50. lua_Number x = luaL_optnumber(L, 2, 1);
  51. lua_pushnumber(L, l_mathop(atan2)(y, x));
  52. return 1;
  53. }
  54. static int math_toint (lua_State *L) {
  55. int valid;
  56. lua_Integer n = lua_tointegerx(L, 1, &valid);
  57. if (valid)
  58. lua_pushinteger(L, n);
  59. else {
  60. luaL_checkany(L, 1);
  61. lua_pushnil(L); /* value is not convertible to integer */
  62. }
  63. return 1;
  64. }
  65. static void pushnumint (lua_State *L, lua_Number d) {
  66. lua_Integer n;
  67. if (lua_numbertointeger(d, &n)) /* does 'd' fit in an integer? */
  68. lua_pushinteger(L, n); /* result is integer */
  69. else
  70. lua_pushnumber(L, d); /* result is float */
  71. }
  72. static int math_floor (lua_State *L) {
  73. if (lua_isinteger(L, 1))
  74. lua_settop(L, 1); /* integer is its own floor */
  75. else {
  76. lua_Number d = l_mathop(floor)(luaL_checknumber(L, 1));
  77. pushnumint(L, d);
  78. }
  79. return 1;
  80. }
  81. static int math_ceil (lua_State *L) {
  82. if (lua_isinteger(L, 1))
  83. lua_settop(L, 1); /* integer is its own ceil */
  84. else {
  85. lua_Number d = l_mathop(ceil)(luaL_checknumber(L, 1));
  86. pushnumint(L, d);
  87. }
  88. return 1;
  89. }
  90. static int math_fmod (lua_State *L) {
  91. if (lua_isinteger(L, 1) && lua_isinteger(L, 2)) {
  92. lua_Integer d = lua_tointeger(L, 2);
  93. if ((lua_Unsigned)d + 1u <= 1u) { /* special cases: -1 or 0 */
  94. luaL_argcheck(L, d != 0, 2, "zero");
  95. lua_pushinteger(L, 0); /* avoid overflow with 0x80000... / -1 */
  96. }
  97. else
  98. lua_pushinteger(L, lua_tointeger(L, 1) % d);
  99. }
  100. else
  101. lua_pushnumber(L, l_mathop(fmod)(luaL_checknumber(L, 1),
  102. luaL_checknumber(L, 2)));
  103. return 1;
  104. }
  105. /*
  106. ** next function does not use 'modf', avoiding problems with 'double*'
  107. ** (which is not compatible with 'float*') when lua_Number is not
  108. ** 'double'.
  109. */
  110. static int math_modf (lua_State *L) {
  111. if (lua_isinteger(L ,1)) {
  112. lua_settop(L, 1); /* number is its own integer part */
  113. lua_pushnumber(L, 0); /* no fractional part */
  114. }
  115. else {
  116. lua_Number n = luaL_checknumber(L, 1);
  117. /* integer part (rounds toward zero) */
  118. lua_Number ip = (n < 0) ? l_mathop(ceil)(n) : l_mathop(floor)(n);
  119. pushnumint(L, ip);
  120. /* fractional part (test needed for inf/-inf) */
  121. lua_pushnumber(L, (n == ip) ? l_mathop(0.0) : (n - ip));
  122. }
  123. return 2;
  124. }
  125. static int math_sqrt (lua_State *L) {
  126. lua_pushnumber(L, l_mathop(sqrt)(luaL_checknumber(L, 1)));
  127. return 1;
  128. }
  129. static int math_ult (lua_State *L) {
  130. lua_Integer a = luaL_checkinteger(L, 1);
  131. lua_Integer b = luaL_checkinteger(L, 2);
  132. lua_pushboolean(L, (lua_Unsigned)a < (lua_Unsigned)b);
  133. return 1;
  134. }
  135. static int math_log (lua_State *L) {
  136. lua_Number x = luaL_checknumber(L, 1);
  137. lua_Number res;
  138. if (lua_isnoneornil(L, 2))
  139. res = l_mathop(log)(x);
  140. else {
  141. lua_Number base = luaL_checknumber(L, 2);
  142. #if !defined(LUA_USE_C89)
  143. if (base == l_mathop(2.0))
  144. res = l_mathop(log2)(x); else
  145. #endif
  146. if (base == l_mathop(10.0))
  147. res = l_mathop(log10)(x);
  148. else
  149. res = l_mathop(log)(x)/l_mathop(log)(base);
  150. }
  151. lua_pushnumber(L, res);
  152. return 1;
  153. }
  154. static int math_exp (lua_State *L) {
  155. lua_pushnumber(L, l_mathop(exp)(luaL_checknumber(L, 1)));
  156. return 1;
  157. }
  158. static int math_deg (lua_State *L) {
  159. lua_pushnumber(L, luaL_checknumber(L, 1) * (l_mathop(180.0) / PI));
  160. return 1;
  161. }
  162. static int math_rad (lua_State *L) {
  163. lua_pushnumber(L, luaL_checknumber(L, 1) * (PI / l_mathop(180.0)));
  164. return 1;
  165. }
  166. static int math_min (lua_State *L) {
  167. int n = lua_gettop(L); /* number of arguments */
  168. int imin = 1; /* index of current minimum value */
  169. int i;
  170. luaL_argcheck(L, n >= 1, 1, "value expected");
  171. for (i = 2; i <= n; i++) {
  172. if (lua_compare(L, i, imin, LUA_OPLT))
  173. imin = i;
  174. }
  175. lua_pushvalue(L, imin);
  176. return 1;
  177. }
  178. static int math_max (lua_State *L) {
  179. int n = lua_gettop(L); /* number of arguments */
  180. int imax = 1; /* index of current maximum value */
  181. int i;
  182. luaL_argcheck(L, n >= 1, 1, "value expected");
  183. for (i = 2; i <= n; i++) {
  184. if (lua_compare(L, imax, i, LUA_OPLT))
  185. imax = i;
  186. }
  187. lua_pushvalue(L, imax);
  188. return 1;
  189. }
  190. static int math_type (lua_State *L) {
  191. if (lua_type(L, 1) == LUA_TNUMBER) {
  192. if (lua_isinteger(L, 1))
  193. lua_pushliteral(L, "integer");
  194. else
  195. lua_pushliteral(L, "float");
  196. }
  197. else {
  198. luaL_checkany(L, 1);
  199. lua_pushnil(L);
  200. }
  201. return 1;
  202. }
  203. /*
  204. ** {==================================================================
  205. ** Pseudo-Random Number Generator based on 'xorshift128+'.
  206. ** ===================================================================
  207. */
  208. /* number of binary digits in the mantissa of a float */
  209. #define FIGS l_mathlim(MANT_DIG)
  210. #if FIGS > 64
  211. /* there are only 64 random bits; use them all */
  212. #undef FIGS
  213. #define FIGS 64
  214. #endif
  215. #if !defined(LUA_USE_C89) && defined(LLONG_MAX) && !defined(LUA_DEBUG) /* { */
  216. /*
  217. ** Assume long long.
  218. */
  219. /* a 64-bit value */
  220. typedef unsigned long long I;
  221. static I xorshift128plus (I *state) {
  222. I x = state[0];
  223. I y = state[1];
  224. state[0] = y;
  225. x ^= x << 23;
  226. state[1] = (x ^ (x >> 18)) ^ (y ^ (y >> 5));
  227. return state[1] + y;
  228. }
  229. /* must take care to not shift stuff by more than 63 slots */
  230. #define maskFIG (~(~1LLU << (FIGS - 1))) /* use FIGS bits */
  231. #define shiftFIG (l_mathop(0.5) / (1LLU << (FIGS - 1))) /* 2^(-FIG) */
  232. /*
  233. ** Convert bits from a random integer into a float in the
  234. ** interval [0,1).
  235. */
  236. static lua_Number I2d (I x) {
  237. return (lua_Number)(x & maskFIG) * shiftFIG;
  238. }
  239. /* convert an 'I' to a lua_Unsigned */
  240. #define I2UInt(x) ((lua_Unsigned)(x))
  241. /* convert a lua_Integer to an 'I' */
  242. #define Int2I(x) ((I)(x))
  243. #else /* no long long }{ */
  244. /*
  245. ** Use two 32-bit integers to represent a 64-bit quantity.
  246. */
  247. #if LUAI_BITSINT >= 32
  248. typedef unsigned int lu_int32;
  249. #else
  250. typedef unsigned long lu_int32;
  251. #endif
  252. /* a 64-bit value */
  253. typedef struct I {
  254. lu_int32 h; /* higher half */
  255. lu_int32 l; /* lower half */
  256. } I;
  257. /*
  258. ** basic operations on 'I' values
  259. */
  260. static I pack (int h, int l) {
  261. I result;
  262. result.h = h;
  263. result.l = l;
  264. return result;
  265. }
  266. /* i ^ (i << n) */
  267. static I Ixorshl (I i, int n) {
  268. return pack(i.h ^ ((i.h << n) | (i.l >> (32 - n))), i.l ^ (i.l << n));
  269. }
  270. /* i ^ (i >> n) */
  271. static I Ixorshr (I i, int n) {
  272. return pack(i.h ^ (i.h >> n), i.l ^ ((i.l >> n) | (i.h << (32 - n))));
  273. }
  274. static I Ixor (I i1, I i2) {
  275. return pack(i1.h ^ i2.h, i1.l ^ i2.l);
  276. }
  277. static I Iadd (I i1, I i2) {
  278. I result = pack(i1.h + i2.h, i1.l + i2.l);
  279. if (result.l < i1.l) /* carry? */
  280. result.h++;
  281. return result;
  282. }
  283. /*
  284. ** implementation of 'xorshift128+' algorithm on 'I' values
  285. */
  286. static I xorshift128plus (I *state) {
  287. I x = state[0];
  288. I y = state[1];
  289. state[0] = y;
  290. x = Ixorshl(x, 23); /* x ^= x << 23; */
  291. /* state[1] = (x ^ (x >> 18)) ^ (y ^ (y >> 5)); */
  292. state[1] = Ixor(Ixorshr(x, 18), Ixorshr(y, 5));
  293. return Iadd(state[1], y); /* return state[1] + y; */
  294. }
  295. /*
  296. ** Converts an 'I' into a float.
  297. */
  298. #if FIGS <= 32
  299. /* do not need bits from higher half */
  300. #define maskHF 0
  301. #define maskLOW (~(~1U << (FIGS - 1))) /* use FIG bits */
  302. #define shiftFIG (0.5 / (1U << (FIGS - 1))) /* 2^(-FIG) */
  303. #else /* 32 < FIGS <= 64 */
  304. /* must take care to not shift stuff by more than 31 slots */
  305. /* use FIG - 32 bits from higher half */
  306. #define maskHF (~(~1U << (FIGS - 33)))
  307. /* use all bits from lower half */
  308. #define maskLOW (~0)
  309. /* 2^(-FIG) == (1 / 2^33) / 2^(FIG-33) */
  310. #define shiftFIG ((lua_Number)(1.0 / 8589934592.0) / (1U << (FIGS - 33)))
  311. #endif
  312. #define twoto32 l_mathop(4294967296.0) /* 2^32 */
  313. static lua_Number I2d (I x) {
  314. return ((x.h & maskHF) * twoto32 + (x.l & maskLOW)) * shiftFIG;
  315. }
  316. static lua_Unsigned I2UInt (I x) {
  317. return ((lua_Unsigned)x.h << 31 << 1) | x.l;
  318. }
  319. static I Int2I (lua_Integer n) {
  320. return pack(n, n >> 31 >> 1);
  321. }
  322. #endif /* } */
  323. /*
  324. ** A state uses two 'I' values.
  325. */
  326. typedef struct {
  327. I s[2];
  328. } RanState;
  329. /*
  330. ** Project the random integer 'ran' into the interval [0, n].
  331. ** Because 'ran' has 2^B possible values, the projection can only
  332. ** be uniform when the size of the interval [0, n] is a power of 2
  333. ** (exact division). With the fairest possible projection (e.g.,
  334. ** '(ran % (n + 1))'), the maximum bias is 1 in 2^B/n.
  335. ** For a "small" 'n', this bias is acceptable. (Here, we accept
  336. ** a maximum bias of 0.0001%.) For a larger 'n', we first
  337. ** compute 'lim', the smallest (2^b - 1) not smaller than 'n',
  338. ** to get a uniform projection into [0,lim]. If the result is
  339. ** inside [0, n], we are done. Otherwise, we try we another
  340. ** 'ran' until we have a result inside the interval.
  341. */
  342. #define MAXBIAS 1000000
  343. static lua_Unsigned project (lua_Unsigned ran, lua_Unsigned n,
  344. RanState *state) {
  345. if (n < LUA_MAXUNSIGNED / MAXBIAS)
  346. return ran % (n + 1);
  347. else {
  348. /* compute the smallest (2^b - 1) not smaller than 'n' */
  349. lua_Unsigned lim = n;
  350. lim |= (lim >> 1);
  351. lim |= (lim >> 2);
  352. lim |= (lim >> 4);
  353. lim |= (lim >> 8);
  354. lim |= (lim >> 16);
  355. #if (LUA_MAXINTEGER >> 30 >> 2) > 0
  356. lim |= (lim >> 32); /* integer type has more than 32 bits */
  357. #endif
  358. lua_assert((lim & (lim + 1)) == 0 /* 'lim + 1' is a power of 2 */
  359. && lim >= n /* not smaller than 'n' */
  360. && (lim >> 1) < n); /* it is the smallest one */
  361. while ((ran & lim) > n)
  362. ran = I2UInt(xorshift128plus(state->s));
  363. return ran & lim;
  364. }
  365. }
  366. static int math_random (lua_State *L) {
  367. lua_Integer low, up;
  368. lua_Unsigned p;
  369. RanState *state = (RanState *)lua_touserdata(L, lua_upvalueindex(1));
  370. I rv = xorshift128plus(state->s); /* next pseudo-random value */
  371. switch (lua_gettop(L)) { /* check number of arguments */
  372. case 0: { /* no arguments */
  373. lua_pushnumber(L, I2d(rv)); /* float between 0 and 1 */
  374. return 1;
  375. }
  376. case 1: { /* only upper limit */
  377. low = 1;
  378. up = luaL_checkinteger(L, 1);
  379. if (up == 0) { /* single 0 as argument? */
  380. lua_pushinteger(L, I2UInt(rv)); /* full random integer */
  381. return 1;
  382. }
  383. break;
  384. }
  385. case 2: { /* lower and upper limits */
  386. low = luaL_checkinteger(L, 1);
  387. up = luaL_checkinteger(L, 2);
  388. break;
  389. }
  390. default: return luaL_error(L, "wrong number of arguments");
  391. }
  392. /* random integer in the interval [low, up] */
  393. luaL_argcheck(L, low <= up, 1, "interval is empty");
  394. /* project random integer into the interval [0, up - low] */
  395. p = project(I2UInt(rv), (lua_Unsigned)up - (lua_Unsigned)low, state);
  396. lua_pushinteger(L, p + (lua_Unsigned)low);
  397. return 1;
  398. }
  399. static void setseed (I *state, lua_Integer n) {
  400. int i;
  401. state[0] = Int2I(n);
  402. state[1] = Int2I(~n);
  403. for (i = 0; i < 16; i++)
  404. xorshift128plus(state); /* discard initial values */
  405. }
  406. static int math_randomseed (lua_State *L) {
  407. RanState *state = (RanState *)lua_touserdata(L, lua_upvalueindex(1));
  408. lua_Integer n = luaL_checkinteger(L, 1);
  409. setseed(state->s, n);
  410. return 0;
  411. }
  412. static const luaL_Reg randfuncs[] = {
  413. {"random", math_random},
  414. {"randomseed", math_randomseed},
  415. {NULL, NULL}
  416. };
  417. static void setrandfunc (lua_State *L) {
  418. RanState *state = (RanState *)lua_newuserdatauv(L, sizeof(RanState), 0);
  419. setseed(state->s, 0);
  420. luaL_setfuncs(L, randfuncs, 1);
  421. }
  422. /* }================================================================== */
  423. /*
  424. ** {==================================================================
  425. ** Deprecated functions (for compatibility only)
  426. ** ===================================================================
  427. */
  428. #if defined(LUA_COMPAT_MATHLIB)
  429. static int math_cosh (lua_State *L) {
  430. lua_pushnumber(L, l_mathop(cosh)(luaL_checknumber(L, 1)));
  431. return 1;
  432. }
  433. static int math_sinh (lua_State *L) {
  434. lua_pushnumber(L, l_mathop(sinh)(luaL_checknumber(L, 1)));
  435. return 1;
  436. }
  437. static int math_tanh (lua_State *L) {
  438. lua_pushnumber(L, l_mathop(tanh)(luaL_checknumber(L, 1)));
  439. return 1;
  440. }
  441. static int math_pow (lua_State *L) {
  442. lua_Number x = luaL_checknumber(L, 1);
  443. lua_Number y = luaL_checknumber(L, 2);
  444. lua_pushnumber(L, l_mathop(pow)(x, y));
  445. return 1;
  446. }
  447. static int math_frexp (lua_State *L) {
  448. int e;
  449. lua_pushnumber(L, l_mathop(frexp)(luaL_checknumber(L, 1), &e));
  450. lua_pushinteger(L, e);
  451. return 2;
  452. }
  453. static int math_ldexp (lua_State *L) {
  454. lua_Number x = luaL_checknumber(L, 1);
  455. int ep = (int)luaL_checkinteger(L, 2);
  456. lua_pushnumber(L, l_mathop(ldexp)(x, ep));
  457. return 1;
  458. }
  459. static int math_log10 (lua_State *L) {
  460. lua_pushnumber(L, l_mathop(log10)(luaL_checknumber(L, 1)));
  461. return 1;
  462. }
  463. #endif
  464. /* }================================================================== */
  465. static const luaL_Reg mathlib[] = {
  466. {"abs", math_abs},
  467. {"acos", math_acos},
  468. {"asin", math_asin},
  469. {"atan", math_atan},
  470. {"ceil", math_ceil},
  471. {"cos", math_cos},
  472. {"deg", math_deg},
  473. {"exp", math_exp},
  474. {"tointeger", math_toint},
  475. {"floor", math_floor},
  476. {"fmod", math_fmod},
  477. {"ult", math_ult},
  478. {"log", math_log},
  479. {"max", math_max},
  480. {"min", math_min},
  481. {"modf", math_modf},
  482. {"rad", math_rad},
  483. {"sin", math_sin},
  484. {"sqrt", math_sqrt},
  485. {"tan", math_tan},
  486. {"type", math_type},
  487. #if defined(LUA_COMPAT_MATHLIB)
  488. {"atan2", math_atan},
  489. {"cosh", math_cosh},
  490. {"sinh", math_sinh},
  491. {"tanh", math_tanh},
  492. {"pow", math_pow},
  493. {"frexp", math_frexp},
  494. {"ldexp", math_ldexp},
  495. {"log10", math_log10},
  496. #endif
  497. /* placeholders */
  498. {"random", NULL},
  499. {"randomseed", NULL},
  500. {"pi", NULL},
  501. {"huge", NULL},
  502. {"maxinteger", NULL},
  503. {"mininteger", NULL},
  504. {NULL, NULL}
  505. };
  506. /*
  507. ** Open math library
  508. */
  509. LUAMOD_API int luaopen_math (lua_State *L) {
  510. luaL_newlib(L, mathlib);
  511. lua_pushnumber(L, PI);
  512. lua_setfield(L, -2, "pi");
  513. lua_pushnumber(L, (lua_Number)HUGE_VAL);
  514. lua_setfield(L, -2, "huge");
  515. lua_pushinteger(L, LUA_MAXINTEGER);
  516. lua_setfield(L, -2, "maxinteger");
  517. lua_pushinteger(L, LUA_MININTEGER);
  518. lua_setfield(L, -2, "mininteger");
  519. setrandfunc(L);
  520. return 1;
  521. }