I'm trying to get this to show me the incremental increases for each time hori_dist is being calculated. Instead it is just showing me the final result all added up together. How do i get it to output 5 values since my range is 5?
Googled for videos, searched online, tried this multiple ways
Vx0 = 18
Vy0 = 18
V = 18
Theta = 45
y0 = 1.8
x0 = 0
p = 1.2#given density
C = 0.3#Drag coefficient
dt = 0.2#Time increment
def x_direction (x0, Vx0, dt):
"""Calculate the distance moved in x axis"""
new_dist = 0
for hori_dist in range(5):
hori_dist = x0 + Vx0*dt
new_dist = new_dist + hori_dist
return new_dist
new_dist = x_direction(x0, Vx0, dt)
print ("Distanced moved in x direction is :", new_dist)
To define a scope, many languages use the curly braces { }. Python, however, uses indentation.
So, if you want something to be printed 5 times, you include it inside the for loop. May be this will help you.
Vx0 = 18
Vy0 = 18
V = 18
Theta = 45
y0 = 1.8
x0 = 0
p = 1.2 #given density
C = 0.3 #Drag coefficient
dt = 0.2 #Time increment
def x_direction (x0, Vx0, dt):
"""Calculate the distance moved in x axis"""
new_dist = 0
for hori_dist in range(5):
hori_dist = x0 + Vx0*dt
new_dist = new_dist + hori_dist
print ("[LOOP] Distance being moved is", hori_dist) #The extra print
print ("[LOOP] New distance is", new_dist) #Another extra print
return new_dist
new_dist = x_direction(x0, Vx0, dt)
print ("Distanced moved in x direction is :", new_dist)
Just put a print statement in your loop ,like this
hori_dist = x0 + Vx0*dt
print (hori_dist)
Also, you can't call function like you did here x_direction(x0, Vx0, dt). You should pass values instead of variables x_direction(0, 18, 0.2)
Related
I'm trying to find the area of a space under a curve on a graph. This is being done by getting the area of multiple rectangles with a constant base but incrementing heights. The rectangles are between two endpoints given my the user. The incrementations are from point a and by 0.1 until it reaches point b. My question is, how do I increment the x in a while loop if I can't use a range? I tried using the += bit so x= a+=1 but that gives a syntax error.
print("Computing the area under the curve x^2 + x + 1")
a = int(input("Enter the left end point a: x ="))
b = int(input("Enter the left end point b: x ="))
base = 0.1
x = 0
while (a <= x <= b):
area = (x**2 + x + 1) * base
x += area
Try increment left end point variable a instead of defining and incrementing x.
print("Computing the area under the curve x^2 + x + 1")
a = int(input("Enter the left end point a: x = "))
b = int(input("Enter the right end point b: x = "))
base = 0.1
total_area = 0
while (a <= b):
sub_area = (a**2 + a + 1) * base
total_area += sub_area
a += base
print("The area under the curve is " + str(total_area))
x should be equal to a, because the range of x is from a to b.
In each loop, you have to let a add 0.1.
Set a new variable to record the total area, such as 'total_area' as follows.
print("Computing the area under the curve x^2 + x + 1")
a = int(input("Enter the left end point a: x ="))
b = int(input("Enter the left end point b: x ="))
base = 0.1
x = a # 1
total_area = 0
while (a <= x <= b):
area = (x**2 + x + 1) * base
x += base # 2
total_area += area # 3
print(total_area)
I've created a fatorial function that would help me calculate the taylor expansion of sine. There are no evident mistakes in my code, but the returned value is wrong. That's my code:
PI = 3.14159265358979323846
def fatorial(n):
fatorial = 1
for i in range(1,n+1,1):
fatorial = fatorial * i
return fatorial
def seno(theta):
n = 1
k = 3
eps = 10**-10
theta = (theta*PI)/180
x = ((-1)**n)*((theta)**k)
y = fatorial(k)
while x/y > eps or x/y < -eps:
theta = theta + (x/y)
n = n + 1
k = k + 2
x = ((-1)**n) * ((theta)**k)
y = fatorial(k)
return theta
You are summing theta in the while-loop and therefore using an adjusted angle for the next elements of the Taylor series. Just add a thetas (for the sum) like so (I have taken the liberty to add some performance improvements, no need to recalculate the full factorial, also calculated first elements explicitly and changed the limit check to avoid recalculations of x/y):
import math
PI = 3.14159265358979323846
def fatorial(n):
fatorial = 1
for i in range(1,n+1,1):
fatorial = fatorial * i
return fatorial
def seno(theta):
n = 1
k = 3
#eps = 10**-10
theta = (theta*PI)/180
thetas = theta # <- added this
x = -theta*theta*theta
y = 6
#while x/y > eps or x/y < -eps:
while k < 14:
thetas = thetas + (x/y) # sum thetas
n = n + 1
k = k + 2
#x = ((-1)**n) * ((theta)**k)
x = ((-1)**(n%2)) * ((theta)**k) # but use the original value for the series
#y = fatorial(k)
y *= k * (k-1)
return thetas # return the sum
if __name__ == '__main__':
print(seno(80), math.sin(8*PI/18))
this results in
0.984807753125684 0.984807753012208
I'm rather new to coding and am trying to check whether a dot drawn (in pygame)is on the last line drawn (making the sprouts game).
I have two lists, both holding coordinates of the line segments (in 30pix) just drawn, and one with last dot drawn.
current_line = []
dot_pos = []
Distance function I found online:
def dist_point_to_line(line1, line2, point):
x0 = point[0]
y0 = point[1]
x1 = line1[0]
y1 = line1[1]
x2 = line2[0]
y2 = line2[1]
px = x2-x1
py = y2-y1
norm = px*px + py*py
u = ((x0 - x1) * px + (y0 - y1) * py) / float(norm)
if u > 1:
u = 1
elif u < 0:
u = 0
x = x1 + u * px
y = y1 + u * py
dx = x - x0
dy = y - y0
dist = sqrt(dx*dx + dy*dy)
return dist
Now I want to implement the check at each segment of the line, but I'm stuck. Any advice?
This is what I thought of, though it doesn't want to work:
def distance_check():
for i in range(len(current_line)-1):
if dist_point_to_line(current_line[i], current_line[i+1], dot_pos) < 10:
return True #dot allowed to be placed
return False
If dot_pos is a list then you have to get the last element of the list (dot_pos[-1]). Note the arguments to the function dist_point_to_line are single dots, rather than a list of dots:
def distance_check():
for i in range(len(current_line)-1):
if dist_point_to_line(current_line[i], current_line[i+1], dot_pos[-1]) < 10:
return True #dot allowed to be placed
return False
So I'm trying to make a code that simulates free fall its almost all done except that the code starts at '1' instead of '0'. My code is:
def simulateFreeFall(mass,deltaT,simulationTime):
acceleration = 9.81
velocity = 0
length = 0
velocity1 = 0
length1 = 0
times = []
l = []
v = []
a = []
x = 0
timeStep = simulationTime / deltaT
while x < timeStep:
elapsedTime = deltaT * x
Dvelocity = acceleration * deltaT
velocity1 = Dvelocity + velocity
velocity = velocity1
v.append(velocity1)
a.append(acceleration)
Dlength = velocity1 * deltaT
length1 = Dlength + length
length = length1
l.append(length1)
times.append(elapsedTime)
x += 1
plt.plot(times, l, 'rs')
plt.title("Free Fall - No Friction")
plt.xlabel("Time")
plt.ylabel("Fall Length")
plt.grid(True)
plt.show()
print(l[0])
simulateFreeFall(70,0.01,60)
When I run the code the first length in the list " l " is 0.000981 instead of 0 I'm not sure what I did wrong for it to start at technically what is supposed to be after 0.01 seconds.
You could use some prints to debug this. By using print along the flow you can see what is happening.
Nothing surprising is happening, l[0] is:
l[0] = length1 = Dlength + length = velocity1 * deltaT + lenght =
= (Dvelocity + velocity ) * deltaT + lenght
and the key thing is that
Dvelocity = acceleration * deltaT
which are non-zero
velocity1 is not 0 in the first loop, so length1 is not 0
The reason for this is you calculate the velocity out of the acceleration and your time step which is not 0 in the first step and therefore the first length is neither
I have a 300 x 4 matrix called X created by the odeint function. In the second column are y-values and I would like to cut the matrix when the y-value dips below 0. As a first step I was attempting to create a function that would read the second column and spit out the row number where the column first dips below 0.
X = odeint(func, X0, t)
Yval = X[:,1]
def indexer():
i = 0
if Yval[i] > 0:
i = i + 1
if Yval[i] < 0:
return i
Which is not working and conceptually I know this is wrong, I just couldn't think of another way to do this. Is there a way to cut out all the rows that contain and follow the first <0 y value?
This is my entire code:
import numpy as np
import math
from scipy.integrate import odeint
g = 9.8
theta = (45 * math.pi)/180
v0 = 10.0
k = 0.3
x0 = 0
y0 = 0
vx0 = v0*math.sin(theta)
vy0 = v0*math.cos(theta)
def func(i_state,time):
f = np.zeros(4)
f[0] = i_state[2]
f[1] = i_state[3]
f[2] = -k*(f[0]**2 + f[1]**2)**(.5)*f[0]
f[3] = -g - k*(f[0]**2 + f[1]**2)**(.5)*f[1]
return f
X0 = [x0, y0, vx0, vy0]
t0 = 0
tf = 3
timestep = 0.01
nsteps = (tf - t0)/timestep
t = np.linspace(t0, tf, num = nsteps)
X = odeint(func, X0, t)
Yval = X[:,1]
def indexer():
i = 0
if Yval[i] > 0:
i = i + 1
if Yval[i] < 0:
return i
Maybe you could use the takewhile function from the itertools package:
from itertools import takewhile
first_elements = list(takewhile(lambda x: x[1] >= 0, X))
Where X is your matrix. I used x[1] in the lambda predicate to compare the numbers in the second column.
Here, first_elements will be the rows of the matrix before the first row that contains a value less than zero. You can use len(first_elements) to know what the cutoff point was.
I converted it to a list but you don't have to if you are just going to iterate through the result.
I hope this works.
You could do something like this:
newVals = []
i = 0
while( i < len(X) and X[i][1] >= 0):
newVals.append(X[i])
i += 1
This would go through X and append values to the list newVals until you either reach the end of the list (i < len(X)) or you reach your condition (X[i][1] >= 0).