-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmake_integer.py
More file actions
executable file
·67 lines (44 loc) · 1.28 KB
/
Copy pathmake_integer.py
File metadata and controls
executable file
·67 lines (44 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#!/usr/bin/env python3
import numpy as np
import scipy.optimize as opt
__all__ = ["make_integer"]
def _residualsfrominteger(alpha, vec_in):
"""
Return vec_in*alpha-round(vec_in*alpha)
"""
aux1=vec_in*alpha
aux2=np.empty(len(aux1), dtype=np.float)
np.rint(aux1, aux2)
return aux2-aux1
def make_integer(vec_in):
"""
Given a numpy vector "vec_in", compute alpha such that all components of
alpha*vec_in are on average integer and return
alpha, round(alpha*vec)
"""
#to have a first guess
length=100
x=np.linspace(0.2, 2.0, length)
y=np.empty(length)
for i in range(length):
y[i]=np.linalg.norm(_residualsfrominteger(x[i], vec_in))
#to get the index corresponding to min(y)
mask = (y<min(y)*(1.0+1.0e-15))
aux=x[mask]
param=aux[0]
ris = opt.leastsq( _residualsfrominteger, param, args=(vec_in))
return ris[0][0], np.rint(ris[0][0]*vec_in)
#***************************
# unit testing
if __name__=="__main__":
print("**********************")
print("UNIT TESTING")
print()
scale_in=np.random.uniform(0.8, 1.2)
print("Result has to be "+str(scale_in))
print("")
length=100
vec0=np.random.random_integers(-6, 6, length)
vec1=vec0/scale_in
scale_out, vec_int = make_integer(vec1)
print("Resut="+str(scale_out))