Vandermonde python3 matrix - python-3.x

I wrote a code to compute the vandermonde matrix but I can't get it to print in matrix form. Would really appreciate the help. my code is attached below.
x = [0.55,0.60,0.65,0.70,0.75,0.80,0.85,0.90,0.95,1.00]
col = 10
row = 10
matrix = [[0 for x in range(col)]for y in range(row)]
for i in (range(row)):
matrix[i][0] = 1;
for i in (range(row)):
for j in (1,2,3):
matrix[i][j] = matrix[i][j-1] * x[i]
for i in (range(row)):
for j in (range(col)):
print(matrix[i][j], end = "")
A = ("\n")
print(A)

Related

Adaptive Runge-Kutta 4 method

I am trying to find the solution of DEQ dy/dx = 10*e^(-88.8888889(x-2)^2) - 0.6y.
Function:
def dydx(x,y):
return -0.6*y + 10*np.exp(-(x-2)**2/(2*.075**2))
Single Step Solution:
def direct(x,y,h):
k1 = dydx(x,y)
k2 = dydx(x+h/2, y+k1*h/2)
k3 = dydx(x+h/2, y+k2*h/2)
k4 = dydx(x+h, y+k3*h)
y = y + (1/6)*(k1+2*k2+2*k3+k4)*h
return y
Double Step Solution:
def halving(x,y,h):
h = h/2
xh = np.zeros(3)
yh = np.zeros(3)
xh[0] = x
yh[0] = y
for j in range(0,2):
k1 = dydx(xh[j],yh[j])
k2 = dydx(xh[j]+h/2, yh[j]+k1*h/2)
k3 = dydx(xh[j]+h/2, yh[j]+k2*h/2)
k4 = dydx(xh[j]+h, yh[j]+k3*h)
yh[j+1] = yh[j] + (1/6)*(k1+2*k2+2*k3+k4)*h
xh[j+1] = xh[j] + h
return yh[2]
Find the adaptive step size 'h'
def adapt(x,y,h):
error = abs(direct(x,y,h)) - abs(halving(x,y,h)) # it checks whether h falls between a range or not
if error <= 0.01 and error >= .001:
return h
elif error > 0.01:
return adapt(x,y,h/2) # if error is large recalling adapt function with h/2
elif error < .001:
return adapt(x,y,2*h) # 2*h if error is small
Main Driver Program
def rk4(xi,yi,h,xlim):
nval = int((xlim-xi)/h)
x = np.zeros(nval+1)
y = np.zeros(nval+1)
x[0] = xi
y[0] = yi
for i in range(0,nval):
h = adapt(x[i],y[i],h)
y[i+1] = direct(x[i],y[i],h)
x[i+1] = x[i] + h
return x,y
Evaluate using
rk4(0,0.5,.1,4)
I am using jupyter notebook. This program crashes. Probably the recursion section. But why? The error should have been within range after a few recursive call?

Simpson's rule 3/8 for n intervals in Python

im trying to write a program that gives the integral approximation of e(x^2) between 0 and 1 based on this integral formula:
Formula
i've done this code so far but it keeps giving the wrong answer (Other methods gives 1.46 as an answer, this one gives 1.006).
I think that maybe there is a problem with the two for cycles that does the Riemman sum, or that there is a problem in the way i've wrote the formula. I also tried to re-write the formula in other ways but i had no success
Any kind of help is appreciated.
import math
import numpy as np
def f(x):
y = np.exp(x**2)
return y
a = float(input("¿Cual es el limite inferior? \n"))
b = float(input("¿Cual es el limite superior? \n"))
n = int(input("¿Cual es el numero de intervalos? "))
x = np.zeros([n+1])
y = np.zeros([n])
z = np.zeros([n])
h = (b-a)/n
print (h)
x[0] = a
x[n] = b
suma1 = 0
suma2 = 0
for i in np.arange(1,n):
x[i] = x[i-1] + h
suma1 = suma1 + f(x[i])
alfa = (x[i]-x[i-1])/3
for i in np.arange(0,n):
y[i] = (x[i-1]+ alfa)
suma2 = suma2 + f(y[i])
z[i] = y[i] + alfa
int3 = ((b-a)/(8*n)) * (f(x[0])+f(x[n]) + (3*(suma2+f(z[i]))) + (2*(suma1)))
print (int3)
I'm not a math major but I remember helping a friend with this rule for something about waterplane area for ships.
Here's an implementation based on Wikipedia's description of the Simpson's 3/8 rule:
# The input parameters
a, b, n = 0, 1, 10
# Divide the interval into 3*n sub-intervals
# and hence 3*n+1 endpoints
x = np.linspace(a,b,3*n+1)
y = f(x)
# The weight for each points
w = [1,3,3,1]
result = 0
for i in range(0, 3*n, 3):
# Calculate the area, 4 points at a time
result += (x[i+3] - x[i]) / 8 * (y[i:i+4] * w).sum()
# result = 1.4626525814387632
You can do it using numpy.vectorize (Based on this wikipedia post):
a, b, n = 0, 1, 10**6
h = (b-a) / n
x = np.linspace(0,n,n+1)*h + a
fv = np.vectorize(f)
(
3*h/8 * (
f(x[0]) +
3 * fv(x[np.mod(np.arange(len(x)), 3) != 0]).sum() + #skip every 3rd index
2 * fv(x[::3]).sum() + #get every 3rd index
f(x[-1])
)
)
#Output: 1.462654874404461
If you use numpy's built-in functions (which I think is always possible), performance will improve considerably:
a, b, n = 0, 1, 10**6
x = np.exp(np.square(np.linspace(0,n,n+1)*h + a))
(
3*h/8 * (
x[0] +
3 * x[np.mod(np.arange(len(x)), 3) != 0].sum()+
2 * x[::3].sum() +
x[-1]
)
)
#Output: 1.462654874404461

How to implement LPP function using PULP in python 3.7?

I want to calculate the Linear Programming Problem(LPP) for my Max function and its constraints as below
I used the follwing pulp code in python 3.7.
import random
import pulp
import pandas as pd
L1=[5,10,15]
L2=[1,2,3]
L3=[5,6,7]
n = 10
set_I = range(2, n-1)
set_J = range(2, n)
c = {(i,j): random.normalvariate(0,1) for i in set_I for j in set_J}
a = {(i,j): random.normalvariate(0,5) for i in set_I for j in set_J}
l = {(i,j): random.randint(0,10) for i in set_I for j in set_J}
u = {(i,j): random.randint(10,20) for i in set_I for j in set_J}
b = {j: random.randint(0,30) for j in set_J}
e={0 or 1 or 0.5}
I=L1
P=L2
C=L3
opt_model = pulp.LpProblem(name="LPP")
# if x is Continuous
x_vars = {(i,j):
pulp.LpVariable(cat=pulp.LpContinuous,
lowBound=l[i,j], upBound=u[i,j],
name="x_{0}_{1}".format(i,j))
for i in set_I for j in set_J}
# if x is Binary
x_vars = {(i,j):
pulp.LpVariable(cat=pulp.LpBinary, name="x_{0}_{1}".format(i,j))
for i in set_I for j in set_J}
# if x is Integer
x_vars = {(i,j):
pulp.LpVariable(cat=pulp.LpInteger,
lowBound=l[i,j], upBound= u[i,j],
name="x_{0}_{1}".format(i,j))
for i in set_I for j in set_J}
# Less than equal constraints
constraints = {j :
pulp.LpConstraint(
e=pulp.lpSum(a[i,j] * x_vars[i,j] for i in set_I),
sense=pulp.pulp.LpConstraintLE,
rhs=b[j],
name="constraint_{0}".format(j))
for j in set_J}
# >= constraints
constraints = {j :
pulp.LpConstraint(
e=pulp.lpSum(a[i,j] * x_vars[i,j] for i in set_I),
sense=pulp.LpConstraintGE,
rhs=b[j],
name="constraint_{0}".format(j))
for j in set_J}
# == constraints
constraints = {j :
pulp.LpConstraint(
e=pulp.lpSum(a[i,j] * x_vars[i,j] for i in set_I),
sense=pulp.LpConstraintEQ,
rhs=b[j],
name="constraint_{0}".format(j))
for j in set_J}
objective = pulp.lpSum(x_vars[i,j] * ((e*I*(C[i])) + (1-e)* P(i) )
for i in set_I
for j in set_J)
# for maximization
opt_model.sense = pulp.LpMaximize
opt_model.setObjective(objective)
# solving with CBC
opt_model.solve()
# solving with Glpk
opt_model.solve(solver = GLPK_CMD())
opt_df = pd.DataFrame.from_dict(x_vars, orient="index",
columns = ["variable_object"])
opt_df.index =pd.MultiIndex.from_tuples(opt_df.index,names=
["column_i", "column_j"])
opt_df.reset_index(inplace=True)
opt_df["solution_value"] = opt_df["variable_object"].apply(lambda
item: item.varValue)
opt_df.drop(columns=["variable_object"], inplace=True)
opt_df.to_csv("./optimization_solution.csv")
I am beginner to LPP and PULP. So I implemented first 2 equations only up to my knowledge.That code also gives me error as below
TypeError: can't multiply sequence by non-int of type 'set'
How to add the constraints of equations 3 and 4 to my code and resolve my error. Also guide me whether my code is correct or not where I want to modify to satisfy the Max function.. Thanks in advance.

Python3 QR Factorization

I am fairly new to python3. I am trying to learn it on my free time before I take a class in the fall. This exercise has been the hardest I've tried. I am trying to take the code and rewrite it in simple form using for loops and not using NUMPY. The end game is to write the code that take a matrix as an argument and computes and prints the QR factorization using the modified schmidt algorithm. Any help would be appreciated. Thank you in advance.
#sample matrix
A = [[80,75,85],
[75,80,75],
[80,80,80]]
#function to find QR factorization of a square matrix
#parameter - matrix to be factorized
def findQRFactorization(A):
#check if A is a matrix
if any(isinstance(i,list) for i in A):
print("Is a matrix")
#number of rows and columns in A
rows = len(A)
cols = len(A[0])
print("rows:",rows," cols:",cols)
#check if A is square matrix
if rows != cols:
print("Not a square matrix. Aborting...")
else:
print("A square matrix. proceeding...")
#create an Identiry matrix of size rows x cols
I = [[0]*cols for i in range(rows)]
for i in range(rows):
I[i][i] = 1
#print(I)
#calculation of QR factorization based on householder reflection method
#QR factorization represents A as A = QR where Q is a orthogonal matrix
#while R is a upper triangular matrix.
#Initialize Q and R
Q = [[0.0] * cols for i in range(rows)]
R = A
#print("Q:",Q)
#print("R:",R)
#loop to perform QR factorization
for k in range(rows-1):
#calculate x, e
x = [row[k] for row in R[k:]]
e = [row[k] for row in I[k:]]
#calculate norm of x
norm_x = math.sqrt(sum([i**2 for i in x]))
#print("norm x:",norm_x)
#calculate alpha
sign = lambda x: (1, -1)[x < 0]
alpha = -sign(x[0])*norm_x
#print('alpha:',alpha)
#calculate minor matrix of u and v
u = list(map(lambda i,j: i + alpha * j, x, e))
norm_u = math.sqrt(sum([i**2 for i in u]))
v = list(map(lambda i: i/norm_u, u))
#calculate Q
Q_minor = [ [float(i==j) - 2.0 * v[i] * v[j] for i in range(rows-k)] for j in range(cols-k) ]
def Q_identity(Q_minor,i,j,k):
if i < k or j < k:
return float(i == j)
else:
return Q_minor[i-k][j-k]
Q_padded = [[Q_identity(Q_minor,i,j,k) for i in range(rows)] for j in range(cols)]
#update Q and R
def multiply(P,Q):
return [[sum(elemp * elemq for elemp, elemq in zip(rowp, colq)) for colq in zip(*Q)] for rowp in P]
if k == 0:
Q = Q_padded
R = multiply(Q_padded,A)
else:
Q = multiply(Q_padded,Q)
R = multiply(Q_padded,R)
#calculate transpose of Q
Q_dash = [[Q[i][j] for i in range(cols)] for j in range(rows)]
print("QR factorization of ",A)
print("Q: ",Q_dash)
print("R: ",R)
else:
print("Not a matrix. QR factorization not possible.")
#call function
findQRFactorization(A)

Smoothing values (neighbors between 1-9)

Instructions: Compute and store R=1000 random values from 0-1 as x. moving_window_average(x, n_neighbors) is pre-loaded into memory from 3a. Compute the moving window average for x for the range of n_neighbors 1-9. Store x as well as each of these averages as consecutive lists in a list called Y.
My solution:
R = 1000
n_neighbors = 9
x = [random.uniform(0,1) for i in range(R)]
Y = [moving_window_average(x, n_neighbors) for n_neighbors in range(1,n_neighbors)]
where moving_window_average(x, n_neighbors) is a function as follows:
def moving_window_average(x, n_neighbors=1):
n = len(x)
width = n_neighbors*2 + 1
x = [x[0]]*n_neighbors + x + [x[-1]]*n_neighbors
# To complete the function,
# return a list of the mean of values from i to i+width for all values i from 0 to n-1.
mean_values=[]
for i in range(1,n+1):
mean_values.append((x[i-1] + x[i] + x[i+1])/width)
return (mean_values)
This gives me an error, Check your usage of Y again. Even though I've tested for a few values, I did not get yet why there is a problem with this exercise. Did I just misunderstand something?
The instruction tells you to compute moving averages for all neighbors ranging from 1 to 9. So the below code should work:
import random
random.seed(1)
R = 1000
x = []
for i in range(R):
num = random.uniform(0,1)
x.append(num)
Y = []
Y.append(x)
for i in range(1,10):
mov_avg = moving_window_average(x, n_neighbors=i)
Y.append(mov_avg)
Actually your moving_window_average(list, n_neighbors) function is not going to work with a n_neighbors bigger than one, I mean, the interpreter won't say a thing, but you're not delivering correctness on what you have been asked.
I suggest you to use something like:
def moving_window_average(x, n_neighbors=1):
n = len(x)
width = n_neighbors*2 + 1
x = [x[0]]*n_neighbors + x + [x[-1]]*n_neighbors
mean_values = []
for i in range(n):
temp = x[i: i+width]
sum_= 0
for elm in temp:
sum_+= elm
mean_values.append(sum_ / width)
return mean_values
My solution for +100XP
import random
random.seed(1)
R=1000
Y = list()
x = [random.uniform(0, 1) for num in range(R)]
for n_neighbors in range(10):
Y.append(moving_window_average(x, n_neighbors))

Resources