I have some code that I need help vectorizing.
I want to convert the following to vector form, how can I? I want to get rid of the inner loop - apparently, it's possible to do so.
X is an NxD matrix. y is a 1xD vector.
def foo(X, y, mylambda, N, D, epsilon):
...
for j in xrange(D):
aj = 0
cj = 0
for i in xrange(N):
aj += 2 * (X[i,j] ** 2)
cj += 2 * (X[i,j] * (y[i] - w.transpose()*X[i].transpose() + w[j]*X[i,j]))
...
If I call numpy.vectorize() on the function, it throws an error at runtime.
Complete code:
import scipy
import scipy.io
import numpy
from numpy import linalg
from scipy import *
def data(N, d, k, sigma, seed=12231):
random.seed(seed)
X = randn(N, d)
wg = zeros(1 + d)
wg[1:k + 1] = 10 * sign(randn(k))
eps = randn(N) * sigma
y = X.dot(wg[1:]) + wg[0] + eps
return (y, X)
def foo(X, y, mylambda, n, D, epsilon):
identityMatrix = numpy.matrix(numpy.identity(D))
w = (X.transpose() * X + mylambda * identityMatrix).getI() * X.transpose() * y
newweight = (X.transpose() * X + mylambda * identityMatrix).getI() * X.transpose() * y
iterate = 1
iteration = 0
while iterate > 0 and iteration < 10000:
iteration += 1
iterate = 0
maxerror = 0
for j in xrange(D):
aj = 0
cj = 0
for i in xrange(n):
aj += 2 * (X[i,j] ** 2)
cj += 2 * (X[i,j] * (y[i] - w.transpose()*X[i].transpose() + w[j]*X[i,j]))
if cj < -mylambda:
newweight[j,0] = (cj + mylambda)/ aj
elif cj > mylambda:
newweight[j,0] = (cj - mylambda)/ aj
else:
newweight[j,0] = 0
if abs(newweight[j,0] - w[j,0]) > epsilon:
iterate += 1
if abs(newweight[j,0] - w[j,0]) > maxerror:
maxerror = abs(newweight[j,0] - w[j,0])
w[j,0] = newweight[j,0]
N, D, k = 50, 75, 5
(y, X) = data(N, D, k, 1, 123)
X = numpy.matrix(X)
y = numpy.matrix(y).transpose()
foo(X, y, 1, N, D, 0.1)
You can replace:
aj = 0
cj = 0
for i in xrange(n):
aj += 2 * (X[i,j] ** 2)
cj += 2 * (X[i,j] * (y[i] - w.transpose()*X[i].transpose() + w[j]*X[i,j]))
with:
aj = 2*np.sum(X[:,j].T*X[:,j])
cj = 2*np.sum(np.multiply(X[:, j].T, (y.T - w.T*X.T + w[j] * X[:, j].T)))
Related
I have used the Equation of Motion (Newtons Law) for a simple spring and mass scenario incorporating it into the given 2nd ODE equation y" + (k/m)x = 0; y(0) = 3; y'(0) = 0.
I have then been able to run a code that calculates and compares the Exact Solution with the Runge-Kutta Method Solution.
It works fine...however, I have recently been asked not to separate my values of 'x' and 'v', but use a single vector 'x' that has two dimensions ( i.e. 'x' and 'v' can be handled by x(1) and x(2) ).
MY CODE:
# Given is y" + (k/m)x = 0; y(0) = 3; y'(0) = 0
# Parameters
h = 0.01; #Step Size
t = 100.0; #Time(sec)
k = 1;
m = 1;
x0 = 3;
v0 = 0;
# Exact Analytical Solution
te = np.arange(0, t ,h);
N = len(te);
w = (k / m) ** 0.5;
x_exact = x0 * np.cos(w * te);
v_exact = -x0 * w * np.sin(w * te);
# Runge-kutta Method
x = np.empty(N);
v = np.empty(N);
x[0] = x0;
v[0] = v0;
def f1 (t, x, v):
x = v
return x
def f2 (t, x, v):
v = -(k / m) * x
return v
for i in range(N - 1): #MAIN LOOP
K1x = f1(te[i], x[i], v[i])
K1v = f2(te[i], x[i], v[i])
K2x = f1(te[i] + h / 2, x[i] + h * K1x / 2, v[i] + h * K1v / 2)
K2v = f2(te[i] + h / 2, x[i] + h * K1x / 2, v[i] + h * K1v / 2)
K3x = f1(te[i] + h / 2, x[i] + h * K2x / 2, v[i] + h * K2v / 2)
K3v = f2(te[i] + h / 2, x[i] + h * K2x / 2, v[i] + h * K2v / 2)
K4x = f1(te[i] + h, x[i] + h * K3x, v[i] + h * K3v)
K4v = f2(te[i] + h, x[i] + h * K3x, v[i] + h * K3v)
x[i + 1] = x[i] + h / 6 * (K1x + 2 * K2x + 2 * K3x + K4x)
v[i + 1] = v[i] + h / 6 * (K1v + 2 * K2v + 2 * K3v + K4v)
Can anyone help me understand how I can create this single vector having 2 dimensions, and how to fix my code up please?
You can use np.array() function, here is an example of what you're trying to do:
x = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
Unsure of your exact expectations of what you are wanting besides just having a 2 lists inside a single list. Though I do hope this link will help answer your issue.
https://www.tutorialspoint.com/python_data_structure/python_2darray.htm?
I'm trying to understand the Karatsuba multiplication algorithm. I've written the following code:
def karatsuba_multiply(x, y):
# split x and y
len_x = len(str(x))
len_y = len(str(y))
if len_x == 1 or len_y == 1:
return x*y
n = max(len_x, len_y)
n_half = 10**(n // 2)
a = x // n_half
b = x % n_half
c = y // n_half
d = y % n_half
ac = karatsuba_multiply(a, c)
bd = karatsuba_multiply(b, d)
ad_plus_bc = karatsuba_multiply((a+b), (c+d)) - ac - bd
return (10**n * ac) + (n_half * ad_plus_bc) + bd
This test case does not work:
print(karatsuba_multiply(1234, 5678)) ## returns 11686652, should be 7006652
But if I use the following code from this answer, the test case produces the correct answer:
def karat(x,y):
if len(str(x)) == 1 or len(str(y)) == 1:
return x*y
else:
m = max(len(str(x)),len(str(y)))
m2 = m // 2
a = x // 10**(m2)
b = x % 10**(m2)
c = y // 10**(m2)
d = y % 10**(m2)
z0 = karat(b,d)
z1 = karat((a+b),(c+d))
z2 = karat(a,c)
return (z2 * 10**(2*m2)) + ((z1 - z2 - z0) * 10**(m2)) + (z0)
Both functions look like they're doing the same thing. Why doesn't mine work?
It seems that in with kerat_multiply implementation you can't use the correct formula for the last return.
In the original kerat implementation the value m2 = m // 2 is multiplied by 2 in the last return (z2 * 10**(2*m2)) + ((z1 - z2 - z0) * 10**(m2)) + (z0) (2*m2)
So you i think you need either to add a new variable as below where n2 == n // 2 so that you can multiply it by 2 in the last return, or use the original implementation.
Hoping it helps :)
EDIT: This is explain by the fact that 2 * n // 2 is different from 2 * (n // 2)
n = max(len_x, len_y)
n_half = 10**(n // 2)
n2 = n // 2
a = x // n_half
b = x % n_half
c = y // n_half
d = y % n_half
ac = karatsuba_multiply(a, c)
bd = karatsuba_multiply(b, d)
ad_plus_bc = karatsuba_multiply((a + b), (c + d)) - ac - bd
return (10**(2 * n2) * ac) + (n_half * (ad_plus_bc)) + bd
I am trying to calculate g(x_(i+2)) from the value g(x_(i+1)) and g(x_i), i is an integer, assuming I(x) and s(x) are Gaussian function. If we know x_i = 100, then the summation from 0 to 100, I don't know how to handle g(x_i) with the subscript in python, knowing the first and second value, we can find the third value, after n cycle, we can find the nth value.
Equation:
code:
import numpy as np
from matplotlib import pyplot as p
from math import pi
def f_s(x, mu_s, sig_s):
ss = -np.power(x - mu_s, 2) / (2 * np.power(sig_s, 2))
return np.exp(ss) / (np.power(2 * pi, 2) * sig_s)
def f_i(x, mu_i, sig_i):
ii = -np.power(x - mu_i, 2) / (2 * np.power(sig_i, 2))
return np.exp(ii) / (np.power(2 * pi, 2) * sig_i)
# problems occur in this part
def g(x, m, mu_s, sig_s, mu_i, sig_i):
for i in range(1, m): # specify the number x, x_1, x_2, x_3 ......X_m
h = (x[i + 1] - x[i]) / e
for n in range(0, x[i]): # calculate summation
sum_f = (f_i(x[i], mu_i, sig_i) - f_s(x[i] - n, mu_s, sig_s) * g_x[n]) * np.conj(f_s(n +
x[i], mu_s, sig_s))
g_x[1] = 1 # initial value
g_x[2] = 5
g_x[i + 2] = h * sum_f + 2 * g_x[i + 1] - g_x[i]
return g_x[i + 2]
x = np.linspace(-10, 10, 10000)
e = 1
d = 0.01
m = 1000
mu_s = 2
sig_s = 1
mu_i = 1
sig_i = 1
p.plot(x, g(x, m, mu_s, sig_s, mu_i, sig_i))
p.legend()
p.show()
result:
I(x) and s(x)
import math
import numpy as np
S0 = 100.; K = 100.; T = 1.0; r = 0.05; sigma = 0.2
M = 100; dt = T / M; I = 500000
S = np.zeros((M + 1, I))
S[0] = S0
for t in range(1, M + 1):
z = np.random.standard_normal(I)
S[t] = S[t - 1] * np.exp((r - 0.5 * sigma ** 2) * dt + sigma *
math.sqrt(dt) * z)
C0 = math.exp(-r * T) * np.sum(np.maximum(S[-1] - K, 0)) / I
print ("European Option Value is ", C0)
It gives a value of around 10.45 as you increase the number of simulations, but using the B-S formula the value should be around 10.09. Anybody know why the code isn't giving a number closer to the formula?
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
# Prototype of N-R for a system of two non-linear equations
#evaluating functions of two variables
# f(x,y)=1.6 * x ** 2 + 3.6 * x * y - 7.8 * x - 2.6 * y + 5.2
# g(x,y)=0.9 * y ** 2 + 3.1 * x **2 - 6.2 * x + 6.2 * y
# x = 0.5
# y =0.4
from math import *
eq1 = raw_input('Enter the equation 1: ')
eq2 = raw_input('Enter the equation 2: ')
x0 = float(input('Enter x: '))
y0 = float(input('Enter y: '))
def f(x,y):
return eval(eq1)
def g(x,y):
return eval(eq2)
Ea_X = 1
x = x0
y = y0
for n in range(1, 8):
a = (f(x + 1e-06, y) - f(x,y)) / 1e-06 #in this one start the trouble
b = (f(x, y + 1e-06) - f(x,y)) / 1e-06
c = 0 - f(x,y)
d = (g(x + 1e-06, y) - g(x,y)) / 1e-06
eE = (g(x, y + 1e-06) - g(x,y)) / 1e-06
f = 0 - g(x,y)
print "f(x, y)= ", eq1
print "g(x, y)= ", eq2
print """x y """
print x, y
print """a b c d e f """
print a, b, c, d, e, f
print """
a * x + b * y = c
d * x + e * y = f
"""
print a," * x + ",b," * y = ",c
print d," * x + ",eE," * y = ",f
_Sy = (c - a * f / d) / (b - a * eE / d)
_Sx = (f / d) - (eE / d) * _Sy
Ea_X = (_Sx ** 2 + _Sy ** 2)**0.5
x = x + _Sx
y = y + _Sy
print "Sx = ", _Sx
print "Sy = ", _Sy
print "x = ", x
print "y = ", y
print "|X_1 - X_0| = ", Ea_X
I've been testing the Newton-Rapson method for two non-linear equations,
the prototype code works but then I was thinking in making it more
useful, because the prototype is about the input of the 2 equations
and the first guesses, and it would be good to implement a for loop
instead of starting the process like 6 or 10 to resolve just one
of the so many equations that I'm working with
# Prototype of N-R for a system of two non-linear equations
# f(x,y)=1.6 * x ** 2 + 3.6 * x * y - 7.8 * x - 2.6 * y + 5.2
# g(x,y)=0.9 * y ** 2 + 3.1 * x **2 - 6.2 * x + 6.2 * y
# x = 0.5
# y =0.4
# evaluating functions of two variables
from math import *
eq1 = raw_input('Enter the equation 1: ')
eq2 = raw_input('Enter the equation 2: ')
x0 = float(input('Enter x: '))
y0 = float(input('Enter y: '))
def f(x,y):
return eval(eq1)
def g(x,y):
return eval(eq2)
Ea_X = 1
x = x0
y = y0
a = (f(x + 1e-06, y) - f(x,y)) / 1e-06
b = (f(x, y + 1e-06) - f(x,y)) / 1e-06
c = 0 - f(x,y)
d = (g(x + 1e-06, y) - g(x,y)) / 1e-06
eE = (g(x, y + 1e-06) - g(x,y)) / 1e-06
f = 0 - g(x,y)
print "f(x, y)= ", eq1
print "g(x, y)= ", eq2
print """x y """
print x, y
print """a b c d e f """
print a, b, c, d, e, f
print """
a * x + b * y = c
d * x + e * y = f
"""
print a," * x + ",b," * y = ",c
print d," * x + ",eE," * y = ",f
_Sy = (c - a * f / d) / (b - a * eE / d)
_Sx = (f / d) - (eE / d) * _Sy
Ea_X = (_Sx ** 2 + _Sy ** 2)**0.5
x = x + _Sx
y = y + _Sy
print "Sx = ", _Sx
print "Sy = ", _Sy
print "x = ", x
print "y = ", y
print "|X_1 - X_0| = ", Ea_X
In the line
f = 0 - g(x,y)
you assign a number to the name f. Since functions and other variables share a namespace in Python (a function is just a callable object, bound to any variable), this makes future iterations fail. Pick another name for the value you're assigning in the above line.
Here is the problem:
f = 0 - g(x,y)
You are rebinding f from a function to a float.