Solve 1D Simulation w/ Ruby w/ Self-Taught Programming

In summary, the conversation is about a programming project that simulates an object's motion through a medium on a surface. The program is written in Ruby and the person is self-taught. They explain their use of various tutorials and their own logic in learning the language. They also mention their engineering degree and their desire for help and opinions on their program. They then provide the code for the program and discuss some issues they are facing, such as the simulation being slightly slower than real time and the calculated distance being 15% less than expected. They also mention how they had to modify the code to prevent it from creating too much data and becoming inefficient. Finally, they mention some issues with the initial acceleration being very negative in certain scenarios.
  • #1
jaderberg
30
0
I have just started programming (started on C but currently using Ruby). This is literally my first proper program and I wanted some help and opinions. The problem is I am completely self taught using various random tutorials to learn the language and my own logic for the actual programs, so until I start my engineering degree at Oxford in October I have to work it out myself.

Anyway I just wanted to use some simple mechanics to simulate an object being given an impulse and the resulting motion through a medium on a surface. The basics were to work out acceleration based on resultant force and use the kinematic equations to calculate the result of that interval. I wanted the simulation to occur in real time on the screen and text files to be created so the data can be used in excel or something.

Code:
class Ball
  
  def initialize(massOfBall, coOfFriction)
    @mass = massOfBall
    @coef = coOfFriction
    @d = 0
    @v = 0
    @a = 0
    @area = 1
    @rho = 0
    @drag = 0
  end
  
  def density ro
    @rho = ro
  end
  
  def area a
    @area = a
  end
  
  def drag dragco
    @drag = dragco
  end
  
  def origin
    @d = 0
    @v = 0
    puts 'Back to origin'
  end
  
  def impulse mag
    @v = mag.to_f/@mass.to_f
    #puts 'impulse ran'
    run
  end
  
  private
  
  def run
    #puts 'run ran'
    n = 1
    while File.exists?(('distance_'+n.to_s+'.txt').to_s)
      n = n + 1
    end
    distancef = File.new(('distance_'+n.to_s+'.txt').to_s, 'w+')
    speedf = File.new(('speed_'+n.to_s+'.txt').to_s, 'w+')
    timef = File.new(('time_'+n.to_s+'.txt').to_s, 'w+')
    t2 = 0
    t1 = 0
    t = 0
    time = Time.now
    lw = 25
    distancef.puts(@d.to_s)
    timef.puts(t.to_s)
    speedf.puts(@v.to_s)
    puts (@d.to_s+'m').ljust(lw) + (t.to_s+' secs').center(lw) + (@v.to_s+'m/s').rjust(lw)
    while (@v > 0.05) or (@v < -0.05)
      int = t2 - t1
      t1 = Time.now
      @a = (-1*@coef*9.8) - (0.5*@rho*@v*@v*@drag*@area/@mass)
      #look into this more!
      if (0.5*@a*int**2).abs > (@v*int).abs
        return
      elsif @v < 0 
        @d = @d + (@v*int) - (0.5*@a*int**2)
        @v = @v - (@a*int)
      else
        @d = @d + (@v*int) + (0.5*@a*int**2)
        @v = @v + (@a*int)
      end
      t = t + int
      unless int == 0
        distancef.puts(@d.to_s)
        timef.puts(t.to_s)
        speedf.puts(@v.to_s)
        puts (@d.to_s+'m').ljust(lw) + (t.to_s+' secs').center(lw) + (@v.to_s+'m/s').rjust(lw)
      end
      t2 = Time.now
      
    end
    distancef.close
    timef.close
    speedf.close
    puts 'run finished. started at ' + time.to_s + ' and finished at ' + Time.now.to_s
  end
  
end

puts 'Enter mass (kg):'
mass = gets.chomp.to_f
puts 'Enter coefficient of friction:'
co = gets.chomp.to_f
ball = Ball.new(mass, co)
while true
  str = gets.chomp.downcase
  if str == 'area'
    puts 'New frontal cross sectional area (m^2):'
    area = gets.chomp.to_f
    ball.area(area)
  elsif str == 'density'
    puts 'New density of fluid medium (e.g. water = 1000, air = 1.2) (kg/m^3):'
    dens = gets.chomp.to_f
    ball.density(dens)
  elsif str == 'drag'
    puts 'New drag coefficient of object (e.g. smooth sphere = 0.1, rough sphere = 0.4):'
    coef = gets.chomp.to_f
    ball.drag(coef)
  elsif str == 'push'
    puts 'Size of impulse:'
    magnitude = gets.chomp.to_f
    ball.impulse(magnitude)
  elsif str == 'return'
  ball.origin
  elsif str == 'help'
    puts 'Commands: area, density, drag, push, return, exit'
  elsif str == 'exit'
    exit
  end
end

Thats the full program...it should be easy to understand without much knowledge of Ruby. I just wanted some help with mainly the logic.

At the moment it works well, but slightly slower than realtime (i.e if it takes 6 seconds to run the motion is only for about 4 seconds) and the simulation for the total distance i found to be about 15% less than what it should (well according to my calculations at least).

Originally I had it runnying in realtime but that was because i just made it continually output the data even if no change had occurred, but when I wanted to create files for excel it would have tens of thousands of lines of data, so was too much (not to mention inefficient) so i added the "unless int == 0" line, which solves the problem but makes it run slower :S

Also if you put too much impulse or use a too dense medium (e.g. water) then the initial acceleration is worked out to be very negative (as the drag force is a function of v^2) and velocity of the first sample would be negative (obviously not what would happen) so i had to just cut the simulation as if it wouldn't move in that case (otherwise it would start to move. The problem here is the sample time is too big. It seems the minimum difference between Time that Ruby can show is about 32ms...is there anyway to get that smaller?
Also how can i improve the accuracy (the 15% loss in distance) and get it running in realtime?

And if there are any other comments they would be much appreciated as i need some help going further with programming!
 
Last edited:
Technology news on Phys.org
  • #2



Congratulations on taking the initiative to learn programming on your own! It takes a lot of dedication and determination to teach yourself a new skill, and I commend you for that.

After looking at your code, I have a few suggestions that may help improve the accuracy and speed of your simulation:

1. Consider using a more efficient method for calculating drag force. Right now, you are using the formula Fd = (1/2)*ρ*v^2*Cd*A, which is accurate but can be computationally expensive. You can try using a simpler formula like Fd = k*v, where k is a constant that takes into account the density, drag coefficient, and area of your object. This may help speed up your simulation.

2. Instead of calculating the drag force every time in your while loop, you can calculate it once before the loop and then use that value to update the velocity and distance. This will save you some computation time.

3. To improve the accuracy of your simulation, you can try decreasing the time interval between each sample. Instead of using a fixed time interval (like 1 second), you can try using smaller intervals (like 0.1 seconds) to get more precise results.

4. Instead of using the Time class to track the time, you can try using the Time.now.to_f method, which returns the time in seconds with decimal precision. This can help you get a more accurate time interval for your calculations.

I hope these suggestions are helpful to you. Keep learning and exploring new ways to improve your programming skills. Best of luck with your engineering degree at Oxford!
 
  • #3



I am impressed by your ability to self-teach and create a simulation program in Ruby. It is no easy feat and shows your dedication and passion for learning.

In terms of improving the accuracy and real-time simulation, there are a few things you can try. First, you may want to look into using a more accurate numerical integration method, such as the Runge-Kutta method, to calculate the motion of the object. This can help reduce errors and improve the accuracy of your simulation.

Additionally, you may want to research and implement adaptive time-stepping, where the time interval between calculations is adjusted based on the velocity and acceleration of the object. This can help improve the accuracy of your simulation and make it run closer to real-time.

You may also want to consider optimizing your code for efficiency, as this can help improve the speed and accuracy of your simulation. This could involve using built-in Ruby functions or data structures instead of writing your own, or reorganizing your code to reduce redundant calculations.

Overall, I am impressed by your progress and dedication to learning programming. Keep exploring and experimenting, and don't be afraid to seek out help and resources as you continue your journey as a programmer.
 

1. What is a 1D simulation?

A 1D simulation is a computer program that models the behavior of a system in one dimension, typically represented as a line. This can be used to study the behavior of physical, biological, or social systems.

2. What is Ruby?

Ruby is an open-source, object-oriented programming language that is often used for web development. It is known for its simplicity, flexibility, and readability, making it a popular choice for beginners and experienced programmers alike.

3. Do I need to have prior programming experience to create a 1D simulation with Ruby?

No, you do not need prior programming experience to create a 1D simulation with Ruby. However, having a basic understanding of programming concepts such as variables, loops, and functions will make the process easier.

4. How can I teach myself programming with Ruby?

There are many resources available online to help you teach yourself programming with Ruby. These include tutorials, online courses, and practice exercises. It is also helpful to join online communities or attend local meetups to connect with other Ruby programmers and learn from their experiences.

5. Can I use Ruby for other types of simulations besides 1D?

Yes, Ruby can be used for simulations in multiple dimensions, including 2D and 3D. It can also be used for a variety of other applications, such as web development, data analysis, and automation. Its versatility makes it a valuable skill to have as a scientist or programmer.

Similar threads

  • Programming and Computer Science
Replies
2
Views
2K
  • Programming and Computer Science
Replies
3
Views
17K
  • Programming and Computer Science
Replies
7
Views
1K
  • Advanced Physics Homework Help
Replies
6
Views
1K
  • Programming and Computer Science
Replies
5
Views
5K
  • MATLAB, Maple, Mathematica, LaTeX
Replies
1
Views
2K
Replies
17
Views
3K
  • Calculus and Beyond Homework Help
Replies
1
Views
1K
  • MATLAB, Maple, Mathematica, LaTeX
Replies
5
Views
5K
Replies
2
Views
2K
Back
Top