random.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. if (typeof Test === 'undefined') require('../tester');
  2. Test('random', function () {
  3. var dp, i, msg, r;
  4. BigNumber.config({ CRYPTO: false });
  5. for ( i = 0; i < 4994; i++ ) {
  6. if ( i & 1 ) {
  7. dp = Math.random() * 100 + 1 | 0;
  8. BigNumber.config({ DECIMAL_PLACES: dp });
  9. r = BigNumber.random();
  10. } else {
  11. dp = Math.random() * 100 | 0;
  12. r = BigNumber.random(dp);
  13. }
  14. //Test.write('\n dp: ' + dp + ' r: ' + r.toString());
  15. // Check that the random number r has a maximum of dp decimal places.
  16. if ( r.dp() > dp ) {
  17. msg = 'r.dp() > dp';
  18. // Check 0 <= r < 1
  19. } else if ( r.lt(0) || r.gte(1) ) {
  20. msg = 'r.lt(0) || r.gte(1)';
  21. // Check that the attributes of r are formed correctly.
  22. } else if ( !r.eq( new BigNumber(r) ) || !r.eq( new BigNumber( r.toString() ) ) ) {
  23. msg = '!r.eq( new BigNumber(r) ) || !r.eq( new BigNumber( r.toString() ) )';
  24. }
  25. Test.isTrue( msg === undefined );
  26. if ( msg !== undefined ) {
  27. Test.write('\n Random number r failed integrity test: ' + msg);
  28. Test.write('\n r: ' + r);
  29. Test.write('\n r.c: ' + r.c);
  30. Test.write('\n r.e: ' + r.e);
  31. Test.write('\n r.s: ' + r.s);
  32. Test.write('\n r.dp: ' + r.dp());
  33. Test.write('\n dp: ' + dp);
  34. msg = undefined;
  35. }
  36. }
  37. BigNumber.random(undefined);
  38. BigNumber.random(null);
  39. BigNumber.random(3);
  40. BigNumber.random(0);
  41. Test.isException(function () { BigNumber.random(Infinity) }, 'Infinity');
  42. Test.isException(function () { BigNumber.random('-Infinity') }, "'-Infinity'");
  43. Test.isException(function () { BigNumber.random(NaN) }, 'NaN');
  44. Test.isException(function () { BigNumber.random('ugh') }, "'ugh'");
  45. Test.isException(function () { BigNumber.random(-1) }, "-1");
  46. Test.isException(function () { BigNumber.random({}) }, "{}");
  47. });