Blame view

chap1/1_3_infinite.py 1.53 KB
bfb563e1   Chunk   first commit
1
2
3
__author__ = 'chunk'

import struct
8a43d8ec   Chunk   cc
4
import numpy as np
763affb7   Chunk   staged.
5

bfb563e1   Chunk   first commit
6
from  common import *
e5dbe416   Chunk   staged.
7
8

def float2bits(f, fmt='bin'):
bfb563e1   Chunk   first commit
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
    if fmt == 'hex':
        return hex(struct.unpack('!l', struct.pack('!f', f))[0])
    return bin(struct.unpack('!l', struct.pack('!f', f))[0])


def double2bits(d, fmt='bin'):
    if fmt == 'hex':
        return hex(struct.unpack('!q', struct.pack('!d', d))[0])
    return bin(struct.unpack('!q', struct.pack('!d', d))[0])


def float2bin(num):
    # http://stackoverflow.com/questions/16444726/binary-representation-of-float-in-python-bits-not-hex
    bits = [bin(ord(c)).replace('0b', '').rjust(8, '0') for c in struct.pack('!f', num)]
    print bits
    return ''.join(bits)


def double2bin(num):
    bits = [bin(ord(c)).replace('0b', '').rjust(8, '0') for c in struct.pack('!d', num)]
bfb563e1   Chunk   first commit
29
30
31
32
33
    print bits
    return ''.join(bits)


def infinite_float():
763affb7   Chunk   staged.
34
    s = np.float32(0)
8a43d8ec   Chunk   cc
35
36
    tmp = np.float32(-1)
    i = 0
bfb563e1   Chunk   first commit
37
    while s != tmp:
8a43d8ec   Chunk   cc
38
        i += 1
bfb563e1   Chunk   first commit
39
40
        tmp = s
        s += np.float32(1.0 / i)
8a43d8ec   Chunk   cc
41

bfb563e1   Chunk   first commit
42
    print i, s, tmp, float2bin(s)
e5dbe416   Chunk   staged.
43
44


763affb7   Chunk   staged.
45
46
47
48
49
def infinite_double(n):
    s = np.float64(0)
    for i in range(1, n + 1):
        s += np.float64(1.0 / i)
    return s
e5dbe416   Chunk   staged.
50
51
52
53
54
55
56
57
58
59
60
61
62


def testn0():
    for i in range(100):
        print i, np.log(i)
        if np.log(i) >= 8:
            print i


if __name__ == '__main__':
    # testn0()
    # infinite_float()

bfb563e1   Chunk   first commit
63
64
65
    # i = 1
    # while infinite_double(i) < 16:
    #     i += 1
e5dbe416   Chunk   staged.
66
    # print i, infinite_double(i)
763affb7   Chunk   staged.
67
68
69
70
71
    timer = Timer()
    timer.mark()
    infinite_double(10000000) # 1125899906842624
    timer.report()
    pass
e5dbe416   Chunk   staged.

763affb7   Chunk   staged.

e5dbe416   Chunk   staged.

763affb7   Chunk   staged.

bfb563e1   Chunk   first commit