1

I need to model a spring in Python for one of my classes at the university and it doesn't really work. I've the second order differential equation and I translated it in 2 first order ones to have a system. Can someone look my code and give me an idea about what could I do? For me, the equations are good, I just don't know how to draw it...

from math import pi
from time import sleep
from turtle import *

k=1
m=1

def main():
    L = 5
    total_time = 0
    vo = 0             #Vitesse angulaire initial (rad/s)
    time_step = 0.05        
    while total_time < 100:
        total_time += time_step
        vo += (-k/m) * L * time_step
        L += vo * time_step
        if draw(L): break
        sleep(time_step)

def init():
    setup()
    mode('logo')
    radians()
    speed(0)
    tracer(False)
    hideturtle()

def draw(L):
    if speed() != 0: return True
    clear()
    pendown()
    setheading(L)
    penup()
    pensize(5)
    pencolor('red')
    dot(L * 10)
    home
    update()

if __name__ == '__main__':
    init()
    main()
cromod
  • 1,721
  • 13
  • 26
Isabella P
  • 19
  • 1
  • 1
    if it's just the drawing you want... http://stackoverflow.com/questions/35777581/drawing-a-zigzag-spring-in-java/35779131#35779131 –  Apr 20 '16 at 15:06

1 Answers1

0

Your equations are good, as far as I remember from my physic lessons, but the L variable is varying from -5 to +5, not from 0 to +5.

The dot(radius) function draws a circle. The radius needs to be positive.

Just replace :

dot(L * 10)

by :

dot(51 + L * 10)

(I put "51" instead of "50" to be sure to avoid errors due to crappy approximation of float numbers)

Some little tip : when you don't understand what happens, try to determine the current values of your variables. You could have guessed that L varies from -5 to +5 by adding print("vo:", vo, "L:", L, "total_time:", total_time) in the loop of the main function.

Réchèr
  • 107
  • 4