1. NBody Write a program that simulates the gravitational attraction of n stars moving in 2D...
Fantastic news! We've Found the answer you've been seeking!
Question:
Transcribed Image Text:
1. NBody Write a program that simulates the gravitational attraction of n stars moving in 2D space. The start of the simulation might look like this: The program should animate the position of each star over time. The number of stars will be given as a command-line argument. Stars Each star should initially have a random (x, y) position in the range [0, 800) (i.e., the size of the canvas). It should also have a random velocity (in both x and y directions) in the range (- maxVel, maxVel) and a random mass in the range [0, maxMass). To make the visualization clearer, each star should have a random color. A random color can be created by generating random RGB values in the range [0, 255] and set using new Color(r, b, g) with g.setColor. (Since the background is black, you may want to restrict colors to a brighter range, such as [128, 255].) Each star should be drawn as a filled circle with diameter equal to its mass. Simulation We can simulate the stars' movement by modeling their position and velocity over time. The program will automatically call the action Performed method every 16 ms (which gives us a 60 frames per second animation, since 1000 / 60 = 16). This also represents one timeslice of our simulation, which advances time by dt, 0.1 by default. To update each star's position and velocity, we can approximate the new values by assuming the star's velocity and acceleration are constant over a small enough time interval. If p, v, and a are position, velocity, and acceleration, respectively, then the change in position and velocity are given by: Ap = v.dt Av=a.dt Gravitational force To calculate the acceleration due to gravity, we know f a = f/m. The gravitational force between two masses is given by gm1m2 12 ' = ma (force = mass acceleration), so where g is the gravitational constant, m₁ and m2 are the masses of the two objects, and r² is the square of the distance between them. The force is directional, along a vector pointing from star 1 to star 2 (or vice versa). The vector should be scaled so that it has unit length (i.e., divide its x and y coordinates by the vector's magnitude) before using it along with the gravitational force to update the star's velocity. The magnitude of a vector (x, y) is given by V x² + y². Since we're not using realistic units for mass, position, and velocity, the value of g is somewhat arbitrary. Simulation We can simulate the stars' movement by modeling their position and velocity over time. The program will automatically call the action Performed method every 16 ms (which gives us a 60 frames per second animation, since 1000 / 60 = 16). This also represents one timeslice of our simulation, which advances time by dt, 0.1 by default. To update each star's position and velocity, we can approximate the new values by assuming the star's velocity and acceleration are constant over a small enough time interval. If p, v, and a are position, velocity, and acceleration, respectively, then the change in position and velocity are given by: Ap = v.dt Av = = a.dt Gravitational force To calculate the acceleration due to gravity, we know f = ma (force = mass acceleration), so a = f/m. The gravitational force between two masses is given by f = gm1m2 r2 , where g is the gravitational constant, m₁ and m2 are the masses of the two objects, and r² is the square of the distance between them. The force is directional, along a vector pointing from star 1 to star 2 (or vice versa). The vector should be scaled so that it has unit length (i.e., divide its x and y coordinates by the vector's magnitude) before using it along with the gravitational force to update the star's velocity. The magnitude of a vector (x, y) is given by x² + y². Since we're not using realistic units for mass, position, and velocity, the value of g is somewhat arbitrary. Settings You can tweak the settings to make the simulation look more realistic. Some recommended settings: • maxVel = 10 • maxMass = 10 • dt = 0.1 • Timer interval of 16 ms • Gravitational constant g = 100 • To avoid a "slingshot" effect, set a minimum inter-star distance of 5 (i.e., treat any distances of less than 5 as a distance of 5) You can use NBody.java as a starting point. This draws a single circle that moves from the upper left to lower right. You'll probably want to modify at least the init, paint, and action Performed methods. You're free to create other classes as well. import java.awt.*; import java.awt.event.* import javax.swing.*; public class NBody extends Canvas implements ActionListener { public int n; public int x; r r public int y; public int size; public double dt; public double maxvel; public double maxMass; public void init(int n) { } // Your initialization code here: this.n = n; ☑ = 0 ; y = 0; // Draw a circle centered at (x, y) with radius public void drawCircle (Graphics g, int x, int y, int r) { int d = 2*1; } g.fillOval (x - r, yr, d, d); public void paint (Graphics g). { } // Clear the screen super.paint(g); // Your drawing code here: g.setColor(Color.WHITE); drawCircle(g, x, y, 10); public void actionPerformed (ActionEvent e) { // Your update code here: x++; y++; // Repaint the screen repaint(); Toolkit.getDefaultToolkit ().sync(); } r // Draw a circle centered at (x, y) with radius public void drawCircle(Graphics g, int x, int y, int r) { } int d = 2*1; g.fillOval (x r, yr, d, d); public void paint (Graphics g) { } // Clear the screen super.paint(g); // Your drawing code here: g.setColor(Color.WHITE); drawCircle(g, x, y, 10); public void actionPerformed (ActionEvent e) { } // Your update code here: x++; y++; // Repaint the screen repaint(); Toolkit.getDefaultToolkit ().sync(); public static void main(String[] args) JFrame frame = new JFrame(); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE) i int n = Integer.parseInt(args[0]); NBody nbody = new NBody(); nbody.setBackground (Color.BLACK); nbody.size = 800; 10%; = 10; nbody.maxVel nbody.maxMass = nbody.dt = 0.1; nbody.setPreferredSize(new Dimension (nbody.size, nbody.size)); nbody.init(n); frame.add(nbody); frame.pack(); Timer timer = new Timer (16, nbody); timer.start(); frame.setVisible(true); } } 1. NBody Write a program that simulates the gravitational attraction of n stars moving in 2D space. The start of the simulation might look like this: The program should animate the position of each star over time. The number of stars will be given as a command-line argument. Stars Each star should initially have a random (x, y) position in the range [0, 800) (i.e., the size of the canvas). It should also have a random velocity (in both x and y directions) in the range (- maxVel, maxVel) and a random mass in the range [0, maxMass). To make the visualization clearer, each star should have a random color. A random color can be created by generating random RGB values in the range [0, 255] and set using new Color(r, b, g) with g.setColor. (Since the background is black, you may want to restrict colors to a brighter range, such as [128, 255].) Each star should be drawn as a filled circle with diameter equal to its mass. Simulation We can simulate the stars' movement by modeling their position and velocity over time. The program will automatically call the action Performed method every 16 ms (which gives us a 60 frames per second animation, since 1000 / 60 = 16). This also represents one timeslice of our simulation, which advances time by dt, 0.1 by default. To update each star's position and velocity, we can approximate the new values by assuming the star's velocity and acceleration are constant over a small enough time interval. If p, v, and a are position, velocity, and acceleration, respectively, then the change in position and velocity are given by: Ap = v.dt Av=a.dt Gravitational force To calculate the acceleration due to gravity, we know f a = f/m. The gravitational force between two masses is given by gm1m2 12 ' = ma (force = mass acceleration), so where g is the gravitational constant, m₁ and m2 are the masses of the two objects, and r² is the square of the distance between them. The force is directional, along a vector pointing from star 1 to star 2 (or vice versa). The vector should be scaled so that it has unit length (i.e., divide its x and y coordinates by the vector's magnitude) before using it along with the gravitational force to update the star's velocity. The magnitude of a vector (x, y) is given by V x² + y². Since we're not using realistic units for mass, position, and velocity, the value of g is somewhat arbitrary. Simulation We can simulate the stars' movement by modeling their position and velocity over time. The program will automatically call the action Performed method every 16 ms (which gives us a 60 frames per second animation, since 1000 / 60 = 16). This also represents one timeslice of our simulation, which advances time by dt, 0.1 by default. To update each star's position and velocity, we can approximate the new values by assuming the star's velocity and acceleration are constant over a small enough time interval. If p, v, and a are position, velocity, and acceleration, respectively, then the change in position and velocity are given by: Ap = v.dt Av = = a.dt Gravitational force To calculate the acceleration due to gravity, we know f = ma (force = mass acceleration), so a = f/m. The gravitational force between two masses is given by f = gm1m2 r2 , where g is the gravitational constant, m₁ and m2 are the masses of the two objects, and r² is the square of the distance between them. The force is directional, along a vector pointing from star 1 to star 2 (or vice versa). The vector should be scaled so that it has unit length (i.e., divide its x and y coordinates by the vector's magnitude) before using it along with the gravitational force to update the star's velocity. The magnitude of a vector (x, y) is given by x² + y². Since we're not using realistic units for mass, position, and velocity, the value of g is somewhat arbitrary. Settings You can tweak the settings to make the simulation look more realistic. Some recommended settings: • maxVel = 10 • maxMass = 10 • dt = 0.1 • Timer interval of 16 ms • Gravitational constant g = 100 • To avoid a "slingshot" effect, set a minimum inter-star distance of 5 (i.e., treat any distances of less than 5 as a distance of 5) You can use NBody.java as a starting point. This draws a single circle that moves from the upper left to lower right. You'll probably want to modify at least the init, paint, and action Performed methods. You're free to create other classes as well. import java.awt.*; import java.awt.event.* import javax.swing.*; public class NBody extends Canvas implements ActionListener { public int n; public int x; r r public int y; public int size; public double dt; public double maxvel; public double maxMass; public void init(int n) { } // Your initialization code here: this.n = n; ☑ = 0 ; y = 0; // Draw a circle centered at (x, y) with radius public void drawCircle (Graphics g, int x, int y, int r) { int d = 2*1; } g.fillOval (x - r, yr, d, d); public void paint (Graphics g). { } // Clear the screen super.paint(g); // Your drawing code here: g.setColor(Color.WHITE); drawCircle(g, x, y, 10); public void actionPerformed (ActionEvent e) { // Your update code here: x++; y++; // Repaint the screen repaint(); Toolkit.getDefaultToolkit ().sync(); } r // Draw a circle centered at (x, y) with radius public void drawCircle(Graphics g, int x, int y, int r) { } int d = 2*1; g.fillOval (x r, yr, d, d); public void paint (Graphics g) { } // Clear the screen super.paint(g); // Your drawing code here: g.setColor(Color.WHITE); drawCircle(g, x, y, 10); public void actionPerformed (ActionEvent e) { } // Your update code here: x++; y++; // Repaint the screen repaint(); Toolkit.getDefaultToolkit ().sync(); public static void main(String[] args) JFrame frame = new JFrame(); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE) i int n = Integer.parseInt(args[0]); NBody nbody = new NBody(); nbody.setBackground (Color.BLACK); nbody.size = 800; 10%; = 10; nbody.maxVel nbody.maxMass = nbody.dt = 0.1; nbody.setPreferredSize(new Dimension (nbody.size, nbody.size)); nbody.init(n); frame.add(nbody); frame.pack(); Timer timer = new Timer (16, nbody); timer.start(); frame.setVisible(true); } }
Expert Answer:
Answer rating: 100% (QA)
A Java code that simulates the gravitational attraction of stars in 2D space import javaxswing import javaawt import javaawteventActionEvent import javaawteventActionListener import javautilArrayList ... View the full answer
Related Book For
Posted Date:
Students also viewed these programming questions
-
"How might incorporating personalized learning paths for employees impact their skill acquisition and overall performance within an organization's training and development program?"
-
Name the following compounds.
-
At January 1, 2018, Lewis Enterprises has the following individual notes receivable that it is considering for impairment: A $2 million note (including accrued interest) from Bebko Inc. Lewis...
-
What do the possible values of a Poisson random variable x represent?
-
What stimulates the heart to beat?
-
Donnahoo Investments specializes in low-risk government bonds. Identify each of Donnahoos transactions as operating (O), investing (I), financing (F), noncash investing and financing (NIF), or a...
-
$10,000 pesos are invested in the purchase of a machine to produce tortillas and it promises income for the first three months of $5000, $3000 and $5000. What is the rate of return on investment or...
-
Imagine that you are an investor on January 1, 2004, and using the historical data up to that date. Assume that the Global index cannot be included in your portfolio. a. Plot the efficient frontier...
-
37. As segments will alter your data set, you should always maintain an unsegmented Master View. a. True b. False
-
What are the constituent elements comprising the framework of the four-factor theory of emotion?
-
According to the data provided by Cadbury, there are different code types for each non-compliance descriptionfor example, lousy stretch wrap, cancelled lines, late deliveries, damages, etc. Our team...
-
PART I (Both Manual and Using Python (or any other programming language of your choice) For the following three problem, you will first compute solutions by hand (show as many steps as pos- sible,...
-
LSTM networks are: O A subset of RNN networks. O A subset of CNN networks. Time series dependent neural networks. O Oscillators.
-
During the fiscal year ended December 31, 2017, Garden Comfort will be required to make quarterly income tax installment payments of $35,000 Outstanding income taxes from the year ended December 31,...
-
4. (a) Find the unit vector in the direction in which the maximum value of the directional derivatives occurs for the function f(x, y) = x 3xy + 4y? at p = (-2,0).
-
On average there are four traffic accidents in a city during one hour of rush-hour traffic. Use the Poisson distribution to calculate the probability that in one such hour there arc (a) No accidents...
-
Explain the tradeoffs between precise and imprecise interrupts on a superscalar machine.
-
When initializing a global variable in a multithreaded program, a common programming error is to allow a race condition where the variable can be initialized twice. Why could this be a problem?...
-
In which of the four I/O software layers is each of the following done. (a) Computing the track, sector, and head for a disk read. (b) Writing commands to the device registers. (c) Checking to see if...
-
Nestls financial statements are presented in Appendix B. Financial statements of Delfi Limited are presented in Appendix C. Instructions Refer to the financial statements and answer the following...
-
Writing Financial statement information about four different companies is as follows. Instructions a. Determine the missing amounts. (Hint: For example, to solve for (a), Assets Liabilities = Equity...
-
The financial statements of TSMC are presented in Appendix A. The complete annual report, including the notes to the financial statements, is available at the companys website. Instructions Refer to...
Study smarter with the SolutionInn App