My code has a problem. I know what the problem is.
I cant append an array to another array with the append method.
I need to find something else. What is an effective and not complicated way to append an array to an array?
This code should plot the trajectory of a ball that is fired from different angles ( 5 to 85 degrees).
import numpy as np
import matplotlib.pyplot as plt
alpha = np.arange(5,86,5)
v0 = 30
Cd = 1.2
A = 0.02
M = 1.5
gvec = np.array([0,-9.813])
rho = 1.225
dt = 0.01
for a in alpha:
xvec = np.array([0.0,0.0])
vvec = v0 * np.array([np.cos(a),np.sin(a)])
xall = []
while xvec[1] > 0:
V = np.sqrt(np.sum(vvec*vvec))
Dvec = -0.5 * rho * Cd * A * V**2 * vvec /V
accvec = gvec + Dvec/M
vvec = vvec + accvec*dt
xvec = xvec + vvec*dt
xall.append(xvec)
xall = np.array(xall)
plt.plot(xall[:,0] ,xall[:,1])
plt.show()
I would like to create an array " xall" in the following format.
xall are all the coordinates. so this is what i want.
xall = array([x1,y1], [x2,y2], ....... , [xn, yn])
Your code is ok, but the condition of while is somehow wrong.
xvec = np.array([0.0,0.0])
vvec = v0 * np.array([np.cos(a),np.sin(a)])
xall = []
while xvec[1] > 0:
Since you define xvec as many 0's array, the condition for while is not met and just passed. Once you include xvec[1] = 0, you can obtain a plot.
Btw, the sin and cos function treats the angle as radian, so you have to modify a bit
vvec = v0 * np.array([np.cos(np.pi * a / 180), np.sin(np.pi * a / 180)])
and the result will be:
Related
I am trying to apply the quantum coin walk on a 3D grid, with 3 Hadamard coins. However I can't seem to get symmetric results after 3 steps. Is it simply not possible to have a probability distribution which is symmetric with such a coin?
Thank you
ps the implementation is based on http://susan-stepney.blogspot.com/2014/02/mathjax.html and the position vector captures a 3D grid.
pps Has this been attempted on qiskit? I couldn't use the hard coded matrix to get result perfectly symmetric for some reasons...
Not sure I answered your question, but
from the code reference you mentioned, I only changed line 30 to:ax = fig.add_subplot(111, projection = '3d') and line 3 to:from mpl_toolkits.mplot3d import Axes3D
from numpy import *
from matplotlib.pyplot import *
from mpl_toolkits.mplot3d import Axes3D
N = 100 # number of random steps
P = 2*N+1 # number of positions
coin0 = array([1, 0]) # |0>
coin1 = array([0, 1]) # |1>
C00 = outer(coin0, coin0) # |0><0|
C01 = outer(coin0, coin1) # |0><1|
C10 = outer(coin1, coin0) # |1><0|
C11 = outer(coin1, coin1) # |1><1|
C_hat = (C00 + C01 + C10 - C11)/sqrt(2.)
ShiftPlus = roll(eye(P), 1, axis=0)
ShiftMinus = roll(eye(P), -1, axis=0)
S_hat = kron(ShiftPlus, C00) + kron(ShiftMinus, C11)
U = S_hat.dot(kron(eye(P), C_hat))
posn0 = zeros(P)
posn0[N] = 1 # array indexing starts from 0, so index N is the central posn
psi0 = kron(posn0,(coin0+coin1*1j)/sqrt(2.))
psiN = linalg.matrix_power(U, N).dot(psi0)
prob = empty(P)
for k in range(P):
posn = zeros(P)
posn[k] = 1
M_hat_k = kron( outer(posn,posn), eye(2))
proj = M_hat_k.dot(psiN)
prob[k] = proj.dot(proj.conjugate()).real
fig = figure()
ax = fig.add_subplot(111, projection = '3d')
plot(arange(P), prob)
plot(arange(P), prob, 'o')
loc = range(0, P, P // 10) #Location of ticks
xticks(loc)
xlim(0, P)
ax.set_xticklabels(range(-N, N+1, P // 10))
show()
When I compile the following program, Python throws a TypeError: only integer scalar arrays can be converted to a scalar index.
This seems like a relatively straightforward program execution, but I can't seem to resolve it.
Frequency
import matplotlib.pyplot as plt
import numpy as np
def period(n):
#masses
m = [1] * n
#lengths
l = [2] * n
M = sum(m)
num = 2 * math.pi * n
for i in range(n):
dem = dem + math.sqrt(g * m[i]/(l[i] * M))
return num/dem
x = np.arange(1, 10,1)
y = period(x)
plt.plot(x,y)
plt.show()
Let M == sum from j==1 to n of the masses m_j. I expect the program to simply display a plot of period where period(n) is simply defined by the sum from 1 to n of sqrt(g * m_j/(l_j * M)).
Use list comprehension to apply period function to each entry in the x array like this -
y = np.array([period(i) for i in x])
Also, you need to initialize both dem and g -
dem = 0.0
g = 9.8
I am having trouble getting my code to count the correct number of elements from three different arrays, with each array having its own parameter. I would like the element to be counted if its meets all three parameters this is what I have so far
import numpy as np
import random as rand
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111,projection='3d')
n = 10
x0 = np.zeros(n)
y0 = np.zeros(n)
z0 = np.zeros(n)
x1 = np.zeros(n)
y1 = np.zeros(n)
z1 = np.zeros(n)
hit = 0
for k in range (n):
theta = rand.uniform(0.0, np.pi)
phi = rand.uniform(0, (2 * np.pi))
x0[k] = np.sin(phi) * np.cos(theta)
y0[k] = np.sin(phi) * np.sin(theta)
z0[k] = np.cos(theta)
for j in range (n):
theta = rand.uniform(0.0, np.pi)
phi = rand.uniform(0, (2 * np.pi))
x1[j] = np.sin(phi) * np.cos(theta)
y1[j] = np.sin(phi) * np.sin(theta)
z1[j] = np.cos(theta)
for i in range(n):
if np.any(x1[j] > -0.3) and np.any(x1[j] < 0.7) and np.any(y1[j] > -0.3) and np.any(y1[j] <0.7) and np.any(z1[j] > -0.3) and np.any(z1[j] < 0.3):
hit += 1
ax.plot_wireframe([x0[k],x1[j]],[y0[k],y1[j]],[z0[k],z1[j]])
print (hit)
print (x1,y1,z1)
plt.show()
I would like for only the end points to be counted if they meet the three parameters.
Thank you
So I need all the output for 'distance in the program to be in one set so I can perform operations on it. Here is the code, most calculations are irrelevant. Python 3.6.
import json
with open('strings.json') as data_file:
data = json.load(data_file)
from math import sin, cos, sqrt, atan2, radians
R = 6373.0
for i in range(0, 81):
dataPoint = data[i]
dataPoint1 = data [i+1]
coordinate = dataPoint['coordinates']
coordinate1 = dataPoint1['coordinates']
x = coordinate[0]
y = coordinate[1]
x1 = coordinate1[0]
y1 = coordinate1[1]
#Irrelevant math here
import math
lat1 = math.cos(math.radians(x)) #converts degrees of long or latitude into rads
lon1 = math.cos(math.radians(y))
lat2 = math.cos(math.radians(x1))
lon2 = math.cos(math.radians(y1))
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2 #formula for distance
c = 2 * atan2(sqrt(a), sqrt(1 - a))
Here lies the problem-
distance = R * c
SetDist = [distance] #this gives me just the final value of distance
from the iteration, I need all.
print("distance between the 2 points:", distance)
I'd also print the set outside the loop block. Thanks.
I am trying to implement the value iteration algorithm of the Markov Decision Process using python. I have one implementation. But, this is giving me many repeated values for the utilities. My transition matrix is quite sparse. Probably, this is causing the problem. But, I am not very sure if this assumption is correct. How should I correct this?
The code might be pretty shoddy. I am very new to value iteration. So please help me identify problems with my code. The reference code is this :http://carlo-hamalainen.net/stuff/mdpnotes/. I have used the ipod_mdp.py code file. Here is the snippet of my implementation:
num_of_states = 470 #total number of states
#initialization
V1 = [0.25] * num_of_states
get_target_index = state_index[(u'48.137654', u'11.579949')] #each state is a location
#print "The target index is ", get_target_index
V1[get_target_index] = -100 #assigning least cost to the target state
V2 = [0.0] * num_of_states
policy = [0.0] * num_of_states
count = 0.0
while max([abs(V1[i] - V2[i]) for i in range(num_of_states)]) > 0.001:
print max([abs(V1[i] - V2[i]) for i in range(num_of_states)])
print count
for s in range(num_of_states): #for each state
#initialize minimum action to the first action in the list
min_action = actions_index[actions[0]] #initialize - get the action index for the first iteration
min_action_cost = cost[s, actions_index[actions[0]]] #initialize the cost
for w in range(num_of_states):
if (s, state_index[actions[0]], w) in transitions: #if this transition exists in the matrix - non-zero value
min_action_cost += 0.9 * transitions[s, state_index[actions[0]], w] * V1[w]
else:
min_action_cost += 0.9 * 0.001 * V1[w] #if not - give it a small value of 0.001 instead of 0.0
#get the minimum action cost for the state
for a in actions:
this_cost = cost[s, actions_index[a]]
for w in range(num_of_states):
# if index_state[w] != 'm':
if (s, state_index[a], w) in transitions:
this_cost += 0.9 * transitions[s, state_index[a], w] * V1[w]
else:
this_cost += 0.9 * 0.001 * V1[w]
if this_cost < min_action_cost:
min_action = actions_index[a]
min_action_cost = this_cost
V2[s] = min_action_cost
policy[s] = min_action
V1, V2 = V2, V1 #swap
count += 1
Thank you very much.
I am not sure I understand your code fully. I will just leave my implementation here in case someone needs it.
import numpy as np
def valueIteration(R, P, discount, threshold):
V = np.copy(R)
old_V = np.copy(V)
error = float("inf")
while error > threshold:
old_V, V = (V, old_V)
max_values = np.dot(P, old_V).max(axis=1)
np.copyto(V, R + discount * max_values)
error = np.linalg.norm(V - old_V)
return V
S = 30
A = 4
R = np.zeros(S)
# Goal state S-1
R[S-2] = 1
P = np.random.rand(S,A,S)
# Goal state goes to dwell state
P[S-2,:,:] = 0
P[S-2,:,S-1] = 1
P[S-1,:,:] = 0
P[S-1,:,S-1] = 1
for s in range(S-2): #goal and dwell states do not need normalization
for a in range(A):
P[s,a,:] /= P[s,a,:].sum()
V = valueIteration(R,P,0.97,0.001)