OILS / mycpp / examples / test_integers.py View on Github | oilshell.org

74 lines, 41 significant
1#!/usr/bin/env python2
2"""
3integers.py
4"""
5from __future__ import print_function
6
7import os
8from mycpp import mops
9from mycpp.mylib import log
10
11from typing import cast
12
13
14def run_tests():
15 # type: () -> None
16
17 a = 3 + 2
18 print('a = %d' % a)
19
20 # the way to write 1 << 31
21 i1 = mops.LShift(mops.BigInt(1), mops.BigInt(31))
22 i2 = mops.Add(i1, i1)
23 i3 = mops.Add(i2, i1)
24
25 # TODO: %d or %ld doesn't work, and won't work when it becomes arbitrary
26 # size
27 print('i1 = %s' % mops.ToStr(i1))
28 print('i2 = %s' % mops.ToStr(i2))
29 print('i3 = %s' % mops.ToStr(i3))
30 print('')
31
32 # This overflows an int64_t
33 i4 = mops.LShift(mops.BigInt(1), mops.BigInt(63))
34 #print('i4 = %s' % mops.ToStr(i4))
35
36 # Max positive (2 ^ (N-1)) - 1
37 x = mops.LShift(mops.BigInt(1), mops.BigInt(62))
38 y = mops.Sub(x, mops.BigInt(1))
39 max_positive = mops.Add(x, y)
40 print('max_positive = %s' % mops.ToStr(max_positive))
41
42 # Max negative -2 ^ (N-1)
43 z = mops.Sub(mops.BigInt(0), x)
44 max_negative = mops.Sub(z, x)
45 print('max_negative = %s' % mops.ToStr(max_negative))
46
47 # Round trip from string
48 s1 = mops.ToStr(max_negative)
49 print('max_negative string = %s' % s1)
50
51 max_negative2 = mops.FromStr(s1)
52 print('max_negative2 = %s' % mops.ToStr(max_negative2))
53
54 #if max_negative == max_negative2:
55 if mops.Equal(max_negative, max_negative2):
56 print('round trip equal')
57
58 big = mops.IntWiden(a)
59 print('big = %s' % mops.ToStr(big))
60 small = mops.BigTruncate(big)
61 print('small = %d' % small)
62
63
64def run_benchmarks():
65 # type: () -> None
66 pass
67
68
69if __name__ == '__main__':
70 if os.getenv('BENCHMARK'):
71 log('Benchmarking...')
72 run_benchmarks()
73 else:
74 run_tests()