Animate a pendulum: Difference between revisions
m
syntax highlighting fixup automation
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
|||
Line 18:
pendulums.ads:
<
type Float_Type is digits <>;
Gravitation : Float_Type;
Line 36:
Velocity : Float_Type;
end record;
end Pendulums;</
pendulums.adb:
<
package body Pendulums is
package Math is new Ada.Numerics.Generic_Elementary_Functions (Float_Type);
Line 76:
Item.Velocity * Float_Type (Time);
end Update_Pendulum;
end Pendulums;</
example main.adb:
<
with Ada.Calendar;
with Pendulums;
Line 102:
" Y: " & Float'Image (Get_Y (My_Pendulum)));
end loop;
end Main;</
{{out}}
Line 234:
BACK-IF-LT( x, y, Print Circle )
RET
</syntaxhighlight>
{{out}}
<pre>
Line 265:
You can simulate a pseudo graphical mode in an Ubuntu Linux terminal by adding the following lines:
</pre>
<
SYS("gsettings set org.gnome.Terminal.Legacy.Profile:/org/gnome/terminal/legacy/profiles:/:.../ font 'Ubuntu Mono 1'")
Line 275:
SYS("gsettings set org.gnome.Terminal.Legacy.Profile:/org/gnome/terminal/legacy/profiles:/:.../ font 'Ubuntu Mono 12'")
SHOW-CURSOR
</syntaxhighlight>
<pre>
And substituting the holding coordinates of the pendulum:
</pre>
<
// in "Animate a Pendulum"
Line 294:
{bx, by, 10} GOSUB( CIRCLE )
</syntaxhighlight>
=={{header|AutoHotkey}}==
This version doesn't use an complex physics calculation - I found a faster way.
{{libheader|GDIP}}
<
;settings
SizeGUI:={w:650,h:400} ;Guisize
Line 337:
GuiClose:
ExitApp</
=={{header|BASIC}}==
Line 343:
{{trans|Commodore BASIC}}
Two shapes are used to draw and undraw the pendulum. Undrawing and drawing is done on the page that is not being displayed to make the animation flicker free. Animation code is compacted and hoisted to the beginning of the program. Variables are defined for all non-zero values.
<
1 FOR X = PX TO BX STEP (BX - PX) / Z:Y = PY + (X - PX) * (BY - PY) / (BX - PX): DRAW T AT X,Y:X(P,N(P)) = X:Y(P,N(P)) = Y:N(P) = N(P) + 1: NEXT X
2 HCOLOR= T: DRAW B AT BX,BY:X(P,N(P)) = BX:Y(P,N(P)) = BY:A = PEEK (R + P):P = NOT P: POKE U,W + W * P:A = G * SIN (F) / L / H:V = V + A / Z:F = F + V: NEXT Q
Line 363:
80 W = 32
85 H = 50
90 GOTO</
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
<
*FLOAT 64
VDU 23,23,4;0;0;0; : REM Set line thickness
Line 394:
GCOL 3,11
CIRCLE FILL bobX + 24 * SIN(a), bobY - 24 * COS(a), 24
ENDPROC</
==={{header|Commodore BASIC}}===
<
20 THETA = π/2
30 G = 9.81
Line 420:
1000 FOR I=0 TO 39: X$ = X$+CHR$(29): NEXT
1010 FOR I=0 TO 24: Y$ = Y$+CHR$(17): NEXT
1020 RETURN</
==={{header|FreeBASIC}}===
<
Dim As Double theta, g, l, accel, speed, px, py, bx, by
theta = PI/2
Line 444:
Draw String (0,385), "Press any key to quit"
Sleep 10
Loop Until Inkey()<>""</
==={{header|IS-BASIC}}===
<
110 LET THETA=RAD(50):LET G=9.81:LET L=.5
120 CALL INIC
Line 501:
620 CLOSE #I
630 NEXT
640 END DEF</
=={{header|C}}==
{{libheader|GLUT}}
<
#include <math.h>
#include <GL/glut.h>
Line 581:
glutMainLoop();
return 0;
}</
=={{header|C sharp|C#}}==
Line 588:
{{libheader|GDI (System.Drawing)}}
<
using System;
using System.Drawing;
Line 643:
}
}
</syntaxhighlight>
=={{header|C++}}==
{{libheader|wxWidgets}}
File wxPendulumDlg.hpp
<
#ifndef __wxPendulumDlg_h__
#define __wxPendulumDlg_h__
Line 715:
#endif // __wxPendulumDlg_h__
</syntaxhighlight>
File wxPendulumDlg.cpp
<
// ---------------------
/// @author Martin Ettl
Line 830:
Refresh();
}
</syntaxhighlight>
This program is tested with wxWidgets version 2.8 and 2.9.
The whole project, including makefile for compiling on Linux
Line 840:
{{libheader|Swing}} {{libheader|AWT}}
<
(ns pendulum
(:import
Line 904:
(-main)
</syntaxhighlight>
=={{header|Common Lisp}}==
Line 914:
Pressing the spacebar adds a pendulum.
<
(defvar *damping* 0.99 "Deceleration factor.")
Line 958:
(random 90)
(round w 2))
pendulums))))))))</
=={{header|Delphi}}==
{{libheader| Vcl.Forms}}
Line 964:
{{libheader| Vcl.ExtCtrls}}
{{Trans|C#}}
<
unit main;
Line 1,052:
end;
end.</
=={{header|E}}==
Line 1,068:
(This logic is more general than necessary; it is designed to be suitable for a larger application as well.)
<
pragma.syntax("0.9")
Line 1,155:
}
interp.blockAtTop()</
=={{header|EasyLang}}==
Line 1,172:
ang += vel
.
ang = 45</
=={{header|Elm}}==
<
import Collage exposing (..)
import Element exposing (..)
Line 1,247:
, update = update
, subscriptions = subscriptions
}</
Link to live demo: http://dc25.github.io/animatedPendulumElm
=={{header|ERRE}}==
<
PROGRAM PENDULUM
Line 1,288:
END LOOP
END PROGRAM
</syntaxhighlight>
PC version: Ctrl+Break to stop.
Line 1,324:
===DOS32 version===
{{works with|Euphoria|3.1.1}}
<
include misc.e
Line 1,380:
end procedure
animation()</
=={{header|F_Sharp|F#}}==
A nice application of F#'s support for units of measure.
<
open System.Drawing
open System.Windows.Forms
Line 1,465:
[<STAThread>]
Application.Run( new PendulumForm( Visible=true ) )</
=={{header|Factor}}==
Approximation of the pendulum for small swings : theta = theta0 * cos(omega0 * t)
<
locals math math.constants math.functions math.rectangles
math.vectors opengl sequences system ui ui.gadgets ui.render ;
Line 1,509:
[ <pendulum-gadget> "pendulum" open-window ] with-ui ;
MAIN: pendulum-main
</syntaxhighlight>
=={{header|FBSL}}==
<
FBSLSETTEXT(ME, "Pendulum")
Line 1,568:
DeleteObject(SelectObject(CreateCompatibleDC, SelectObject))
DeleteDC(CreateCompatibleDC)
END SUB</
'''Screenshot:'''
[[File:FBSLPendulum.png]]
Line 1,574:
=={{header|Fortran}}==
Uses system commands (gfortran) to clear the screen. An initial starting angle is allowed between 90 (to the right) and -90 degrees (to the left). It checks for incorrect inputs.
<
!Implemented by Anant Dixit (October, 2014)
program animated_pendulum
Line 1,649:
end do
end subroutine
</syntaxhighlight>
A small preview (truncated to a few steps of the pendulum changing direction). Initial angle provided = 80 degrees.
Line 1,935:
=={{header|Groovy}}==
Straight translation of Java solution groovified by removing explicit definitions and converting casts to Groovy as style where needed.
<
import java.awt.*;
import javax.swing.*;
Line 1,988:
}
}
</syntaxhighlight>
=={{header|Go}}==
Using {{libheader|GXUI}} from [https://github.com/google/gxui Github]
<
import (
Line 2,107:
func main() {
gl.StartDriver(appMain)
}</
=={{header|Haskell}}==
{{libheader|HGL}}
<
import Graphics.HGL.Draw.Picture
import Graphics.HGL.Utils
Line 2,138:
v' = v + a' * dt
pts = map (\(_,t,_) -> (toInt.(300+).(300*).cos &&& toInt. (300*).sin) (pi/2+0.6*t) )
$ iterate nextAVT (- (g / l) * sin t, t, 0)</
Usage with <code>ghci</code>:
Line 2,146:
=== Alternative solution ===
{{libheader|Gloss}}
<
-- Initial conditions
Line 2,196:
fps = round (1/dt)
render xs = pictures $ renderPendulum xs
update _ = movePendulum</
=={{header|HicEst}}==
[http://www.HicEst.com/DIFFEQ.htm DIFFEQ] and the callback procedure pendulum numerically integrate the pendulum equation.
The display window can be resized during the run, but for window width not equal to 2*height the pendulum rod becomes a rubber band instead:
<
BobMargins = ALIAS(ls, rs, ts, bs) ! box margins to draw the bob
Line 2,233:
dTheta(1) = Theta(2) ! Theta' = Theta(2) substitution
dTheta(2) = -g/Lrod*SIN(Theta(1)) ! Theta" = Theta(2)' = -g/Lrod*SIN(Theta(1))
END</
== Icon and {{header|Unicon}} ==
Line 2,241:
{{trans|Scheme}}
<
import gui
$include "guih.icn"
Line 2,335:
w.show_modal ()
end
</syntaxhighlight>
=={{header|J}}==
Works for '''J6'''
<
coinsert 'jgl2'
Line 2,381:
)
pend_run'' NB. run animation</
Updated for changes in '''J8'''
<
coinsert 'jgl2'
Line 2,434:
)
pend_run''</
[[File:J_pendulum.gif|320px|pretend the ball is yellow - gifgrabber grabbed a monochrome image for some reason...]]
Line 2,440:
=={{header|Java}}==
{{libheader|Swing}} {{libheader|AWT}}
<
import javax.swing.*;
Line 2,491:
new Thread(p).start();
}
}</
=={{header|JavaScript}}==
Line 2,497:
{{trans|E}} (plus gratuitous motion blur)
<
<title>Pendulum</title>
</head><body style="background: gray;">
Line 2,554:
</script>
</body></html></
===Within SVG===
Line 2,563:
Also we'll use a dimensionless formulation of the problem (taking unit value for the mass, the length and so on).
<
<line id="string" x1="0" y1="0" x2="1" y2="0" stroke="grey" stroke-width="0.05" />
<circle id="ball" cx="0" cy="0" r="0.1" fill="black" />
Line 2,604:
</script>
</svg>
</syntaxhighlight>
=={{header|Julia}}==
Differential equation based solution using the Luxor graphics library.<
using Colors
using BoundaryValueDiffEq
Line 2,653:
Scene(muv, frame, easingfunction=easeinoutcubic)],
creategif=true, pathname=giffilename)
</syntaxhighlight>
=={{header|Kotlin}}==
Conversion of Java snippet.
<
import java.util.concurrent.*
import javax.swing.*
Line 2,702:
val executor = Executors.newSingleThreadScheduledExecutor()
executor.scheduleAtFixedRate(Pendulum(200), 0, 15, TimeUnit.MILLISECONDS)
}</
=={{header|Liberty BASIC}}==
<
WindowWidth = 400
WindowHeight = 300
Line 2,746:
[quit.main]
close #main
end</
=={{header|Lingo}}==
<
global velocity, acceleration, angle, posX, posY
Line 2,791:
img.draw(point(200, 100), point(posX, posY), [#color:rgb(0,0,0)])
img.fill(point(posX-20, posY-20), point(posX+20, posY+20), [#shapeType:#oval,#lineSize:1,#bgColor:rgb(0,0,0),#color:rgb(255,255,0)])
end</
=={{header|Logo}}==
{{works with|UCB Logo}}
<
make "L 1
make "bob 10
Line 2,823:
hideturtle
until [key?] [step.pendulum]</
=={{header|Lua}}==
Needs LÖVE 2D Engine
<
function degToRad( d )
return d * 0.01745329251
Line 2,856:
g.circle( "fill", posX, posY, 20 )
end
</syntaxhighlight>
=={{header|M2000 Interpreter}}==
<
Module Pendulum {
back()
Line 2,907:
}
Pendulum
</syntaxhighlight>
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
Animate[Graphics[
List[{Line[{{0, 0}, length {Sin[T], -Cos[T]}} /. {T -> (Pi/6) Cos[2 Pi freq t]}], PointSize[Large],
Point[{length {Sin[T], -Cos[T]}} /. {T -> (Pi/6) Cos[2 Pi freq t]}]}],
PlotRange -> {{-0.3, 0.3}, {-0.5, 0}}], {t, 0, 1}, AnimationRate -> 0.07]</
[[File:mmapendulum.gif]]
=={{header|MATLAB}}==
pendulum.m
<
%% User Defined Parameters
Line 2,986:
[rodPivotPoint(2) position(2)]);
end</
=={{header|Nim}}==
Line 2,996:
Conversion from C with some modifications: changing some variable names, adding a display function to make the program work with "freeGlut", choosing another initial angle, etc.
<
import math
Line 3,102:
var argc: cint = 0
initGfx(addr(argc), nil)
glutMainLoop()</
===Gtk3 version===
Line 3,109:
This version uses the same equations but replace OpenGL by Gtk3 with the “gintro” bindings.
<
import math
Line 3,233:
let app = newApplication(Application, "Rosetta.pendulum")
discard app.connect("activate", activate)
discard app.run()</
=={{header|ooRexx}}==
ooRexx does not have a portable GUI, but this version is similar to the Ada version and just prints out the coordinates of the end of the pendulum.
<
pendulum = .pendulum~new(10, 30)
Line 3,274:
::requires rxmath library
</syntaxhighlight>
=={{header|Oz}}==
Inspired by the E and Ruby versions.
<
[QTk] = {Link ['x-oz://system/wp/QTk.ozf']}
Line 3,360:
{Window show}
{Animation go}
</syntaxhighlight>
=={{header|Perl}}==
Line 3,370:
This does not have the window resizing handling that Tcl does.
<
use strict;
use warnings;
Line 3,436:
$canvas->bind('<Destroy>' => sub {$after_id->cancel});
MainLoop;</
=={{header|Phix}}==
Line 3,442:
{{libheader|Phix/online}}
You can run this online [http://phix.x10.mx/p2js/animate_pendulum2.htm here].
<!--<
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\animate_pendulum.exw
Line 3,550:
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<!--</
=={{header|PicoLisp}}==
A minimalist solution. The pendulum consists of the center point '+', and the swinging xterm cursor.
<
(de pendulum (X Y Len)
Line 3,568:
(call 'tput "cup"
(+ Y (*/ Len (cos Angle) 2.2)) # Compensate for aspect ratio
(+ X (*/ Len (sin Angle) 1.0)) ) ) ) )</
Test (hit any key to stop):
<syntaxhighlight lang
=={{header|Portugol}}==
{{trans|FreeBASIC}}
<
programa {
inclua biblioteca Matematica --> math // math library
Line 3,621:
}
</syntaxhighlight>
=={{header|Prolog}}==
SWI-Prolog has a graphic interface XPCE.
<
pendulum :-
Line 3,705:
ND = - D;
ND = D).
</syntaxhighlight>
=={{header|PureBasic}}==
If the code was part of a larger application it could be improved by specifying constants for the locations of image elements.
<
If Not x
MessageRequester("Error", msg)
Line 3,815:
Break
EndSelect
ForEver</
=={{header|Python}}==
Line 3,821:
{{trans|C}}
<
from pygame.locals import *
from math import sin, cos, radians
Line 3,902:
while True:
input(pygame.event.get())
pygame.display.flip()</
===Python: using tkinter===
<
''' Python 3.6.5 code using Tkinter graphical user interface.'''
Line 3,994:
a = Animation(root)
root.mainloop()
</syntaxhighlight>
=={{header|QB64}}==
<
CONST PI = 3.141592
Line 4,092:
'loop the animation until the user presses any key
LOOP UNTIL exit_flag = 1</
=={{header|R}}==
<
pendulum<-function(length=5,radius=1,circle.color="white",bg.color="white"){
Line 4,118:
}
pendulum(5,1,"gold","lightblue")</
=={{header|Racket}}==
<
#lang racket
Line 4,141:
(animate (pendulum))
</syntaxhighlight>
=={{header|Raku}}==
Line 4,148:
Handles window resizing, modifies pendulum length and period as window height changes. May need to tweek $ppi scaling to get good looking animation.
<
use Cairo;
Line 4,237:
}
SDL_Quit();</
=={{header|REXX}}==
Line 4,245:
this version is similar to the '''Ada''' version and just
<br>displays the coordinates of the end of the pendulum.
<
parse arg cycles Plength theta . /*obtain optional argument from the CL.*/
if cycles=='' | cycles=="," then cycles= 60 /*Not specified? Then use the default.*/
Line 4,275:
/*──────────────────────────────────────────────────────────────────────────────────────*/
sin: procedure; parse arg x; x=r2r(x); _=x; numeric fuzz min(5, max(1,digits()-3)); q=x*x
z=x; do k=2 by 2 until p=z; p= z; _= -_*q/(k*k+k); z= z+_; end; return z</
Programming note: the '''SIN''' and '''COS''' functions above are abridged versions.
Line 4,346:
=={{header|Ring}}==
<
# Project : Animate a pendulum
Line 4,426:
paint.drawline(pivotx, pivoty, bobx, boby)
paint.drawellipse(bobx + 24 * sin(a), boby - 24 * cos(a), 24, 24)
</syntaxhighlight>
Output video:
Line 4,458:
The RLaB script that solves the problem is
<
//
// example: solve ODE for pendulum
Line 4,519:
}
</syntaxhighlight>
=={{header|Ruby}}==
Line 4,532:
the Tcl pendulum swings noticibly faster.
<
$root = TkRoot.new("title" => "Pendulum Animation")
Line 4,594:
$canvas.bind('<Destroy>') {$root.after_cancel($after_id)}
Tk.mainloop</
==={{libheader|Shoes}}===
<
@centerX = 160
@centerY = 25
Line 4,653:
@Theta = lastTheta
end
end</
==={{libheader|Ruby/Gosu}}===
<
begin; require 'rubygems'; rescue; end
Line 4,759:
puts e.message, e.backtrace
gets
end</
=={{header|Rust}}==
Line 4,768:
{{libheader|piston_window}}
<
// using version 0.107.0 of piston_window
use piston_window::{clear, ellipse, line_from_to, PistonWindow, WindowSettings};
Line 4,826:
}
}
</syntaxhighlight>
=={{header|Scala}}==
{{libheader|Scala}}
<
import java.util.concurrent.{Executors, TimeUnit}
Line 4,884:
scheduleAtFixedRate(ui.animate, 0, 15, TimeUnit.MILLISECONDS)
}
}</
=={{header|Scheme}}==
Line 4,893:
This is a direct translation of the Ruby/Tk example into Scheme + PS/Tk.
<
;;; R6RS implementation of Pendulum Animation
Line 4,964:
(tk/after 500 animate)
(tk-event-loop tk)))
</syntaxhighlight>
=={{header|Scilab}}==
Line 5,052:
sleep(deltaT*1000)
end
clear i</
=={{header|SequenceL}}==
{{libheader|EaselSL}}
Using the [https://github.com/bethune-bryant/Easel Easel Engine for SequenceL] <br>
<
import <Utilities/Conversion.sl>;
import <Utilities/Math.sl>;
Line 5,124:
point(x, y);
//=============End=Easel=Functions=============================================</
{{out}}
Line 5,131:
=={{header|Sidef}}==
{{trans|Perl}}
<
var root = %s<MainWindow>.new('-title' => 'Pendulum Animation')
Line 5,191:
canvas.bind('<Destroy>' => { after_id.cancel })
%S<Tk>.MainLoop()</
=={{header|smart BASIC}}==
<
'By Dutchman
' --- constants
Line 5,229:
REFRESH ON
RETURN
</syntaxhighlight>
<pre>
We hope that the webmaster will soon have image uploads enabled again so that we can show a screen shot.
Line 5,237:
{{works with|Tcl|8.5}}
==={{libheader|Tk}}===
<
package require Tk
Line 5,316:
bind .c <Configure> {resized %w}
# Callback to stop the animation cleanly when the GUI goes away
bind .c <Destroy> {after cancel $animation}</
=={{header|VBScript}}==
Well, VbScript does'nt have a graphics mode so this is a wobbly textmode pandulum. It should be called from cscript.
<syntaxhighlight lang=vb>
option explicit
Line 5,365:
Loop
End Sub 'draw_line
</syntaxhighlight>
=={{header|Wren}}==
Line 5,371:
{{libheader|DOME}}
{{libheader|Wren-dynamic}}
<
import "dome" for Window
import "math" for Math
Line 5,418:
}
var Game = Pendulum.new(200)</
=={{header|XPL0}}==
<
proc Ball(X0, Y0, R, C); \Draw a filled circle
Line 5,456:
until KeyHit; \keystroke terminates program
SetVid(3); \restore normal text screen
]</
=={{header|Yabasic}}==
<
open window 400, 300
window origin "cc"
Line 5,485:
until(lower$(inkey$(0.02)) = "q")
exit</
=={{header|ZX Spectrum Basic}}==
{{trans|ERRE}}
In a real Spectrum it is too slow. Use the BasinC emulator/editor at maximum speed for realistic animation.
<
20 LET theta=1
30 LET g=9.81
Line 5,506:
1000 PLOT pivotx,pivoty: DRAW bobx-pivotx,boby-pivoty
1010 CIRCLE bobx,boby,3
1020 RETURN</
{{omit from|LFE}}
|