Integral of a triangle function in python

I have just defined a function which is the integral of a given step function, and now I would like to integrate the triangle function obtained.enter image description here jerk:1,-1,1-1 The step function correspond of a given list of successive jerk. For getting the triangle function,

I have used the formula: a(t)=kt+ac with k the Jerk and ac a constant which ensures the continuity and change for each step. But know, if I use the formula v(t)=(1/2)kt^2+ac*t+vc, I get negative value for velocity which is incorrect.

I have found some scipy function which return a number for an integral but I need a curve, do you have any idea of how I could integrate this? tks you


Asked by: Grace182 | Posted: 06-12-2021






Answer 1

You can use scipy.integrate.quad function...

from scipy.integrate import quad

def g(x): # your triangle function
    return abs((x+1)%2-1)

for x in (0.1*i for i in xrange(40)):
    I = quad(g, 0, x)[0]
    print "x = %f -> g(x) = %f -> I(g, 0, x) = %f" % (x, g(x), I)

Is it the thing you are looking for?

@edit:

When the g function is discrete then you can sum the integrates of non-discrete intervals:

from math import floor
from scipy.integrate import quad

I = 0.0
for x in (1.0*i for i in xrange(4)):
    print "x = %f -> g(x) = %f -> I(g, 0, x) = %f" % (x, g(x), I)
    if floor(x) % 2 == 0:
        g = lambda x: 1
    else:
        g = lambda x: -1
    I += quad(g, x, x+1.0)[0]

Answered by: Lucas739 | Posted: 07-01-2022



Answer 2

This may be what your are looking for :

enter image description here

import numpy as np
import matplotlib.pyplot as plt
from scipy import integrate

# step Function
def jerkstep(xprime,k):
    return (1 - 2*( int(xprime)%2 == 1 ) )*k

# Triangle function ( step integration)
def jerkint(x,k,ac): 
    return  integrate.quad( jerkstep ,0, x, args =(k) )[0] + ac*x

# Integrate of triangle
def jerkintint(x,k,ac,vc):
    return integrate.quad( jerkint, 0 , x , args = (1,0) )[0] + vc*x

# linearly spaced time samples (~ x axis)
t = np.linspace(2.0, 10.0, num = 100)

#optional arguments
k = 1
ac = 0
vc = 0

#output functions
jerk = np.array(t);
triangle = np.array(t);
curve = np.array(t);

# Warning : it can be long ( integration not optimized )
for indice,time in zip(range(len(t)),t): # Double indexation on t indices and t values
    print "Time, in seconds : ", time

    jerk[indice] = jerkstep(time,k)
    print "Step function : " , jerk[indice]

    triangle[indice] =jerkint(time,k,ac)
    print "Step function integrate ( = triangle ) : " , triangle[indice]

    curve[indice] = jerkintint(time,k,ac,vc)
    print "Step function double integrate ( = triangle integrate ) : " , curve[indice]
    print "\n"


# plot figure in mathplotlib
fig, axs = plt.subplots(3, 1, sharex=True, sharey=False)
axs[0].plot(t, jerk, 'o-', label=str("Step Function"))
axs[1].plot(t, triangle, 'o-' , label=str("Triangle Function"))
axs[2].plot(t, curve, 'o-' , label=str("Curve Function"))
fig.show()
plt.show()

Answered by: Emily549 | Posted: 07-01-2022



Similar questions

python - How do I overlap widgets with the Tkinter pack geometry manager?

I want to put a Canvas with an image in my window, and then I want to pack widgets on top of it, so the Canvas acts as a background. Is it possible to have two states for the pack manager: one for one set of widgets and another for another set?


Good geometry library in python?

Closed. This question does not meet Stack Overflow guid...


python - Postgis - How do i check the geometry type before i do an insert

i have a postgres database with millions of rows in it it has a column called geom which contains the boundary of a property. using a python script i am extracting the information from this table and re-inserting it into a new table. when i insert in the new table the script bugs out with the following: Traceback (most recent call last): File "build_parcels.py", line 258, in <module>...


python - How do I use Django to insert a Geometry Field into the database?

class LocationLog(models.Model): user = models.ForeignKey(User) utm = models.GeometryField(spatial_index=True) This is my database model. I would like to insert a row. I want to insert a circle at point -55, 333. With a radius of 10. How can I put this circle into the geometry field? Of course, then I would want to check which circles overlap a given circle. (my select stat...


Help with Windows Geometry in Python

Why are the commands to change the window position before and after sleep(3.00) being ignored? if self.selectedM.get() == 'Bump': W1 = GetSystemMetrics(1) + 200 print W1 w1.wm_geometry("+100+" + str(W1)) w2.wm_geometry("+100+" + str(W1)) w3.wm_geometry("+100+" + str(W1)) w4.wm_geometry("+100+" + str(W1)) self.rvar.set(0) self.rvar2.set(0) ...


python - Parsing MSDN Geometry Data Type

I have a database where one field gives spatial coordinates. I have learned the field is a serialised MSDN geometry Data Type (http://msdn.microsoft.com/en-us/library/bb933973.aspx). I want to access this database from Python and was wandering if anyone knew the format of the Geometry Data Type, or any libraries capable of parsing ...


python - GUI layout using Tk Grid Geometry Manager

Building a small application for personal use with Python and thought I'd try my hand with a little GUI programming using Tkinter. This is the GUI I've created so far: Application doubts: How can I make sure that the three LableFrames - A, B and C in the screenshot - have the same width? (Or rather, have ...


python - Is there a GUI design app for the Tkinter / grid geometry?

Closed. This question does not meet Stack Overflow guid...


geometry - Python - Pygame Drawing Angle

I need to draw an angle(in Pygame), given it's 1. Measure of the angle (θ) 2. Endpoints of the base(A & B) Here I know 1. Measure of θ (in radians and degrees) 2. (x,y) of A and B 3. Measure of BC My Question How do I calculate the position of the Co-ordinates(...


python - Convert Point Geometry to list

I have the following script that creates a point geometry. How can I convert this point geometry to a list only containing the coordiantes to look like [258432.79138201929, 1001957.4394514663]? >>> import ogr >>> driver = ogr.GetDriverByName('ESRI Shapefile') >>> pointshp = driver.Open('U:/My Documents/Tool/shp/point.shp', 0) >>> pointlyr = pointshp.GetLayer...






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top