Page 1 of 1

Sine interpolation

Posted: Sun Nov 16, 2008 5:31 pm
by Trond
An example of how to use Sin() to interpolate between two points. When the second point is used again with a third point, we can even make a curvy graph plotting.

Code: Select all


tX = 5
Dim Y(tX)

Y(0) = 100
Y(1) = 200
Y(2) = 30
Y(3) = 120
Y(4) = 300
Y(5) = 100

Procedure.d DegToRad(D.d)
  ProcedureReturn D * #PI/180
EndProcedure

Procedure.f Interpolate(A.f, B.f, cX.f)
  ; a  = 1st Number
  ; b  = 2nd Number
  ; cX = Relationship (0 - 1)
  ProcedureReturn b*cX + a*(1-cX)
EndProcedure

Procedure.f InterpolateSine(A.f, B.f, cX.f)
  ; a = 1st Number
  ; b = 2nd Number
  ; v = Relationship (0 - 1)

  ; "Stretch" cx to the correct range for Sin()
  cX = cX * (180*#PI/180) + DegToRad(90)
  ; Pass cX to Sin() and compress the result to the
  ; correct range for Interpolate()
  cX = 1 - ( Sin(cX) + 1 ) / 2
  ProcedureReturn Interpolate(A, B, cX)
EndProcedure

Global pX, pY
Procedure LinePlotStart(X, Y)
  pX = X
  pY = Y
EndProcedure

Procedure LinePlot(X, Y, Col)
  LineXY(pX, pY, X, Y, Col)
  pX = X
  pY = Y
EndProcedure

CreateImage(0, 512, 420)
StartDrawing(ImageOutput(0))
  Box(0, 0, 512, 420, #White)
  For X = 0 To tX
    Circle(X*100, Y(X), 2, #Blue)
  Next
  
  LinePlotStart(0, Y(0))
  
  For X = 0 To tX-1
    For cX = 0 To 100
      
      ; Linear interpolation
      Y = Interpolate(Y(X), Y(X+1), cX/100)
      Plot(X*100+cX, Y, RGB(192, 192, 192))
      
      ; Sine interpolation with line plotting
      Y = InterpolateSine(Y(X), Y(X+1), cX/100)
      LinePlot(X*100+cX, Y, #Red)
    Next
  Next
  
StopDrawing()

OpenWindow(0, 0, 0, 512, 420, "", #PB_Window_ScreenCentered | #PB_Window_SystemMenu)
ImageGadget(0, 0, 0, 0, 0, ImageID(0))

Repeat
  Select WaitWindowEvent()
    Case #PB_Event_CloseWindow
      Break
  EndSelect
ForEver


Posted: Sun Nov 16, 2008 9:01 pm
by flaith
Thanks for the tip :D

Posted: Mon Nov 17, 2008 12:44 am
by einander
Nice!
Tusen takk Trond.

Posted: Mon Nov 17, 2008 9:23 am
by dige
Great!

Posted: Mon Nov 17, 2008 11:25 am
by Psychophanta
I like that idea. :wink:

EDIT: By the way, this is what must be applied to this problem asked by merendo:
http://www.purebasic.fr/english/viewtopic.php?p=224808
much better than my solution there :roll:

Posted: Mon Dec 01, 2008 9:52 am
by idle
could be handy thanks