From: Caleb Clausen Date: 2010-05-29T03:39:04+09:00 Subject: Re: A better way to write this function? On 5/28/10, Jason Lillywhite wrote: > Here is my attempt at Newton's second law in Ruby: > > #c is the drag coefficent > #m is mass > #t is total time elapsed > #dt is time increment > #vi is the starting velocity > > G = 9.8 > > def velocity(c, m, t, dt, vi) > vel = [] > t += dt > steps = t/dt > > steps.times do > v = vi > vi = v + ( G - c/m*v) * dt > vel << v > end > return vel > end > > Is there a better way to do write this function? It seems pretty > straight forward to me so I guess that might be a sign that it is fine > the way it is...? > > What if I needed more speed but still wanted it in Ruby? A couple small speedups. c/m never changes while the loop is running, so compute it once when the loop starts, then reuse the value. And you could replace the times loop by a while loop for another small speedup.... but this is never going to be fast in ruby. If you want fast, use C.