I want to draw sin(θ)*cos(θ), but it doesn't work.
I can draw sin or cos,
but I want to draw sin(θ)*cos(θ) together.
Here is my code
private void button1_Click(object sender, EventArgs e)
{
Graphics drw = this.CreateGraphics();
Pen pen = new Pen(Brushes.Black, 7.0f);
float x1 = 0;
float y1 = 0;
float xoy = 200;
float ef = 20;
for (double i=0;i<40;i+=1)
{
double radi = (float)(i * 180 / Math.PI);
float temp = (float)Math.Cos(radi)*(float)Math.Sin(radi);
drw.DrawLine(pen, x1 * ef, y1 * ef + xoy, ef * (float)i, temp * ef + xoy);
x1 = (float)i;
y1 = temp;
}
}
And I want this result:
You may find it easier to look at the corresponding Parametric Equations.
private void Form1_Paint(object sender, PaintEventArgs e)
{
var g = e.Graphics;
double pi = Math.PI;
int n = 100;
var t = Enumerable.Range(0, n).Select(p => p * 2 * pi / n).ToArray();
var x = t.Select(p => Math.Sin(2 * p) * Math.Cos(p)).ToArray();
var y = t.Select(p => Math.Sin(2 * p) * Math.Sin(p)).ToArray();
Pen pen = new Pen(Brushes.Black, 3);
int scale = 100;
int shift = 100;
for (int i = 0; i < n - 1; i++)
{
g.DrawLine(pen, scale*(float)x[i] + shift,
scale*(float)y[i] + shift,
scale*(float)x[i + 1] + shift,
scale*(float)y[i + 1] + shift);
}
}
Actually, the real function you are looking for is a little bit different... see an example here. Looking at this article about polar flowers, I'm sure it will get pointed to the right direction, and it also contains a full working source code.
Just an example, supposing you use a panel in your form on which to draw the polar flower:
panel.OnPaint += Panel_Paint;
private void Panel_Paint(Object sender, PaintEventArgs e)
{
Double scale = ((Panel)sender).Width / 2.0d;
Double repetitions = Math.Round(scale, 0);
Double basis = (2.0d * Math.PI) / scale;
Double petals = 2.0d;
using (Graphics g = e.Graphics)
{
using (Pen pen = new Pen(Brushes.Red, 2.0f))
{
for (Double i = 0.0f; i < (repetitions - 1); ++i)
{
Double t0 = i*basis;
Double t1 = (i + 1)*basis;
Double x0 = Math.Sin(petals * t0) * Math.Cos(t0);
Double x1 = Math.Sin(petals * t1) * Math.Cos(t1);
Double y0 = Math.Sin(petals * t0) * Math.Sin(t0);
Double y1 = Math.Sin(petals * t1) * Math.Sin(t1);
g.DrawLine
(
pen,
(Single) ((scale*x0) + scale),
(Single) ((scale*y0) + scale),
(Single) ((scale*x1) + scale),
(Single) ((scale*y1) + scale)
);
}
}
}
}
The basic formulation states that if the petals variable value is:
even, then it represents half the amount of petals of the polar flower
odd, then it represents the amount of petals of the polar flower
so if you define Double petals = 2.0d;, you will obtain 4 petals... and if you define Double petals = 5.0d;, you will obtain 5 petals.
I tried to convert a csv file to shapefile with its projection. Conversion works but I can't create the .prj file.
The error says that
"there is no source code available for current location".
My code is as follows:
public Form1() {
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e) {
AxMap axMap1 = new AxMap();
Shapefile sf = new Shapefile();
bool result = sf.CreateNewWithShapeID("", ShpfileType.SHP_POLYGON);
if (!result) {
MessageBox.Show(sf.get_ErrorMsg(sf.LastErrorCode));
} else {
double xMin = 0.0;
double yMin = 0.0;
double xMax = 1000.0;
double yMax = 1000.0;
Random rnd = new Random(DateTime.Now.Millisecond);
int fldX = sf.EditAddField("x", FieldType.DOUBLE_FIELD, 9, 12);
int fldY = sf.EditAddField("y", FieldType.DOUBLE_FIELD, 9, 12);
int fldArea = sf.EditAddField("area", FieldType.DOUBLE_FIELD, 9, 12);
// In a loop we are creating 100 different points using the box established above.
for (int i = 0; i < 100; i++) {
if (i % 10 == 0) {
Shape shp1 = new Shape();
shp1.Create(ShpfileType.SHP_POLYGON);
sf.EditInsertShape(shp1, ref i);
} else {
double xCenter = xMin + (xMax - xMin) * rnd.NextDouble();
double yCenter = yMin + (yMax - yMin) * rnd.NextDouble();
// random radius from 10 to 100
double radius = 10 + rnd.NextDouble() * 90;
// polygons must be clockwise
Shape shp = new Shape();
shp.Create(ShpfileType.SHP_POLYGON);
for (int j = 0; j < 37; j++) {
Point pnt = new Point();
pnt.x = xCenter + radius * Math.Cos(j * Math.PI / 18);
pnt.y = yCenter - radius * Math.Sin(j * Math.PI / 18);
shp.InsertPoint(pnt, ref j);
}
sf.EditInsertShape(shp, ref i);
sf.EditCellValue(fldX, i, xCenter.ToString());
sf.EditCellValue(fldY, i, yCenter.ToString());
sf.EditCellValue(fldArea, i, Math.PI * radius * radius);
}
}
axMap1.CreateControl();
axMap1.AddLayer(sf, true);
axMap1.ZoomToLayer(0);
sf.Categories.Generate(fldArea, tkClassificationType.ctNaturalBreaks, 7);
ColorScheme scheme = new ColorScheme();
scheme.SetColors2(tkMapColor.Wheat, tkMapColor.Salmon); sf.Categories.ApplyColorScheme(tkColorSchemeType.ctSchemeGraduated, scheme);
axMap1.Redraw();
sf.SaveAs(#"D:\shp1\polygons.shp", null);
sf.Open("D:\\shp1\\polygons.shp");
sf.Projection = (DotSpatial.Projections.KnownCoordinateSystems.Projected.UtmWgs1984.WGS1984UTMZone32N).ToString();
sf.SaveAs(#"D:\shp1\polygons.prj");
}
}
I have a query regarding the best approach to detect when a moving and potentially rotated rectangle passes over a yellow pixel of a Panel's background image.
I have a method which accepts an Image and a Point, and returns true if that point is that of a yellow pixel. I require this colour detection for the function of my game, which resets the car (player) if it drives over the yellow borders of the track. This method is shown below:
private Boolean isYellow(Image image, Point point)
{
Bitmap bitmap = new Bitmap(image);
Color color = bitmap.GetPixel(point.X, point.Y);
return (color.R > 220 && color.G > 220 && color.B < 200);
}
Previously, to detect if the player rectangle passes over yellow, I checked against the location of the rectangle, as provided by the X and Y values of the object. The issue with this is that the location is the top left corner of a horizontal rectangle, meaning the car can drive almost entirely off the track without detection occurring.
I'd like to fix this by checking all points covered by the rectangle. This is not as simple as it may seem as the rectangle is likely to be rotated. My drawing and movement logic is shown below:
public void draw(Graphics g)
{
int dx = rectangle.X + (rectangle.Height / 2);
int dy = rectangle.Y + (rectangle.Width / 2);
g.ScaleTransform(xScale, yScale);
g.TranslateTransform(dx, dy);
g.RotateTransform((float) ((180 * angle) / Math.PI));
g.TranslateTransform(-dx, -dy);
g.DrawImage(image, rectangle.X, rectangle.Y);
g.ResetTransform();
}
public void move(uRaceGame game, Panel panel)
{
double cos = Math.Cos(angle), sin = Math.Sin(angle);
int xLocation = 200;
int yLocation = 200;
xLocation = (int) Math.Floor(rectangle.X + (cos * game.moveDir * 60));
yLocation = (int) Math.Floor(rectangle.Y + (sin * game.moveDir * 60));
angle = (angle + (game.rotateDir * (Math.PI / 128))) % (Math.PI * 2);
if (xLocation * xScale > panel.Width - (rectangle.Width * cos) || yLocation * yScale > panel.Height - (rectangle.Width * sin) - 5 || xLocation * xScale < 0 || yLocation * yScale < 5) return;
rectangle.Location = new Point(xLocation, yLocation);
}
I tried but failed to create a method which translates the coords of the corner and figures out the middle of the rectangle, but this does not work, and the yellow detection fires in very obscure places:
public Point getCentre()
{
int cX = (int) (rectangle.X + ((rectangle.Width / 2) / xScale)), cY = (int) (rectangle.Y + ((rectangle.Height / 2) / yScale));
float tempX = (rectangle.X - cX), tempY = (rectangle.Y - cY);
double rX = (tempX * Math.Cos(angle)) - (tempY * Math.Sin(angle));
double rY = (tempX * Math.Sin(angle)) - (tempY * Math.Cos(angle));
return new Point((int) ((rX + cX) * xScale), (int) ((rY + cY) * yScale));
}
I'd really appreciate any suggestions on how to tackle this. I included the translation and yellow detection code in case I'm miles off in my attempt and someone else has a better idea.
Thank you very much.
There are two approaches that come to my mind:
You can create loops that go along the tilted sides of the car rectangle
Or you can copy the car to an untilted bitmap and loop over it normally.
Here is an example of the second approach.
It uses a LockBits method that detects Yellow with your code in a Bitmap.
And it prepares that bitmap by copying it from the original BackgroundImage un-rotated.
Here is the result, including a control Panel that shows the untilted Rectangle:
Here is the yellow finder function. It uses Lockbits for speed:
using System.Runtime.InteropServices;
using System.Drawing.Imaging;
public bool testForYellowBitmap(Bitmap bmp)
{
Size s1 = bmp.Size;
PixelFormat fmt = new PixelFormat();
fmt = bmp.PixelFormat;
Rectangle rect = new Rectangle(0, 0, s1.Width, s1.Height);
BitmapData bmp1Data = bmp.LockBits(rect, ImageLockMode.ReadOnly, fmt);
byte bpp1 = 4;
if (fmt == PixelFormat.Format24bppRgb) bpp1 = 3;
else if (fmt == PixelFormat.Format32bppArgb) bpp1 = 4; else return false; // throw!!
int size1 = bmp1Data.Stride * bmp1Data.Height;
byte[] data1 = new byte[size1];
System.Runtime.InteropServices.Marshal.Copy(bmp1Data.Scan0, data1, 0, size1);
for (int y = 0; y < s1.Height; y++)
{
for (int x = 0; x < s1.Width; x++)
{
Color c1;
int index1 = y * bmp1Data.Stride + x * bpp1;
if (bpp1 == 4)
c1 = Color.FromArgb(data1[index1 + 3], data1[index1 + 2],
data1[index1 + 1], data1[index1 + 0]);
else c1 = Color.FromArgb(255, data1[index1 + 2],
data1[index1 + 1], data1[index1 + 0]);
if (c1.R > 220 && c1.G > 220 && c1.B < 200)
{ bmp.UnlockBits(bmp1Data); return true; }
}
}
bmp.UnlockBits(bmp1Data);
return false;
}
I prepare the Bitmap to compare in the MouseMove. The variables w, h, w2, h2 hold the width, height and halves of that of the car's size. The source bitmap is in drawPanel1.BackgroundImage. The current angle is in a TrackBar tr_a.Value. For further control I also display the rotated car rectangle in White.
private void drawPanel1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button.HasFlag(MouseButtons.Left))
{
Size sz = drawPanel1.BackgroundImage.Size;
Rectangle rectSrc = new Rectangle(e.X - w2, e.Y - h2, w, h);
Rectangle rectTgt = new Rectangle(e.X - w, e.Y - h, 2 * w, 2 * h);
using (Graphics g = drawPanel1.CreateGraphics()) // start optional
{
g.TranslateTransform(e.X, e.Y);
g.RotateTransform(trb_a.Value);
g.TranslateTransform(-e.X, -e.Y);
drawPanel1.Refresh();
g.DrawRectangle(Pens.White, rectSrc);
}
using (Graphics g = drawPanel2.CreateGraphics())
{ // end optional
using (Bitmap bmp = new Bitmap(sz.Width, sz.Height))
using (Graphics g2 = Graphics.FromImage(bmp))
{
g2.TranslateTransform(e.X, e.Y);
g2.RotateTransform(-trb_a.Value);
g2.TranslateTransform(-e.X, -e.Y);
g2.DrawImage(drawPanel1.BackgroundImage, rectTgt, rectTgt,
GraphicsUnit.Pixel);
drawPanel2.Refresh();
g.DrawImage(bmp, rectSrc, rectSrc, GraphicsUnit.Pixel);
Text = testForYellowBitmap(bmp) ? "!!YELLOW!!" : "";
}
}
}
The first approach would use a similar LockBits method, but with loops inside that go along the rotated sides of the car rectangle, using floats wth the loop variables to calculate the x-coordinates. Those data should be prepared on each change of car size or angle. The code is a little longer but should be a bit faster, too.
The advantage if the second approach is that by using a ClippingRegion on the Graphics object one could check an arbitrary shape while the first method can be easily modified for concave polygons but not for curved shapes.
Here is the adapted version of the checking code for the first version:
public bool testForYellowBitmapTilt(Bitmap bmp, List<int> leftPts,
List<int> rightPts, Point topLeft)
{
Size s1 = bmp.Size;
PixelFormat fmt = new PixelFormat();
fmt = bmp.PixelFormat;
Rectangle rect = new Rectangle(0, 0, s1.Width, s1.Height);
BitmapData bmp1Data = bmp.LockBits(rect, ImageLockMode.ReadOnly, fmt);
byte bpp1 = 4;
if (fmt == PixelFormat.Format24bppRgb) bpp1 = 3;
else if (fmt == PixelFormat.Format32bppArgb) bpp1 = 4;
else return false; // or throw!!
if (leftPts.Count != rightPts.Count) return false; // or throw!!
int size1 = bmp1Data.Stride * bmp1Data.Height;
byte[] data1 = new byte[size1];
System.Runtime.InteropServices.Marshal.Copy(bmp1Data.Scan0, data1, 0, size1);
for (int y = 0; y < (leftPts.Count); y++)
{
for (int x = leftPts[y] + topLeft.X; x < rightPts[y] + topLeft.X; x++)
{
Color c1;
int index1 = (y + topLeft.Y) * bmp1Data.Stride + x * bpp1;
if (index1 > 0)
{
if (bpp1 == 4)
c1 = Color.FromArgb(data1[index1 + 3], data1[index1 + 2],
data1[index1 + 1], data1[index1 + 0]);
else c1 = Color.FromArgb(255, data1[index1 + 2],
data1[index1 + 1], data1[index1 + 0]);
if (c1.R > 220 && c1.G > 220 && c1.B < 200)
{ bmp.UnlockBits(bmp1Data); return true; }
}
}
}
bmp.UnlockBits(bmp1Data);
return false;
}
The left- and rightside coordinates are stored here:
List<int> leftPts = new List<int>();
List<int> rightPts = new List<int>();
Point top = Point.Empty;
void getOuterPoints(List<PointF> corners, out List<int> leftPts,
out List<int> rightPts, out Point top)
{
leftPts = new List<int>();
rightPts = new List<int>();
PointF left = corners.Select(x => x).OrderBy(x => x.X).First();
PointF right = corners.Select(x => x).OrderByDescending(x => x.X).First();
top = Point.Round(corners.Select(x => x).OrderBy(x => x.Y).First());
PointF bottom = corners.Select(x => x).OrderByDescending(x => x.Y).First();
int w1 = -(int)(top.X - left.X);
int w2 = -(int)(left.X - bottom.X );
int h1 = (int)(left.Y - top.Y);
int h2 = (int)(bottom.Y - left.Y);
float d1 = 1f * w1 / h1;
float d2 = 1f * w2 / h2;
for (int y = 0; y < h1; y++) leftPts.Add( (int)(y * d1) );
for (int y = 0; y < h2; y++) leftPts.Add( (int)(y * d2 + w1));
for (int y = 0; y < h2; y++) rightPts.Add( (int)(y * d2));
for (int y = 0; y < h1; y++) rightPts.Add( (int)(y * d1 + w2));
}
You need to feed in the four corners as a List<PointF> in any order; the top can be anything, it will be set in the method. The coodinates are relative to the car, so they don't change when the car moves..
Ive been trying to make an simple mandelbrot renderer just to get myself into c# and forms, but when i render the image the program runs out of memory sometimes.
The memory builds up to 2GB and then crashes.
But sometimes it builds up i a jigsaw pattern like this and dont crash:
http://puu.sh/l2ri9/2fcd47e6d7.png
==============Code to render================
Renderer.CreateGraphics().Clear(Color.White);
double minR = System.Convert.ToDouble(MinR.Value);
double maxR = System.Convert.ToDouble(MaxR.Value);
double minI = System.Convert.ToDouble(MaxI.Value);
double maxI = System.Convert.ToDouble(MinI.Value);
int maxN = System.Convert.ToInt32(Iterations.Value);
SolidBrush MandelColor = new SolidBrush(Color.Red);
for (int y = 0; y < Renderer.Height; y++)
{
for (int x = 0; x < Renderer.Width; x++)
{
double cr = fitInRRange(x, Renderer.Width, minR, maxR);
double ci = fitInIRange(y, Renderer.Height, minI, maxI);
int n = findMandelbrot(cr, ci, maxN);
double t = ((n + 0.0) / (maxN + 0.0));
MandelColor.Color = Color.FromArgb(System.Convert.ToInt32(9 * (1 - t) * t * t * t * 255), System.Convert.ToInt32(15 * (1 - t) * (1 - t) * t * t * 255), System.Convert.ToInt32(8.5 * (1 - t) * (1 - t) * (1 - t) * t * 255));
Renderer.CreateGraphics().FillRectangle(MandelColor, x, y, 1, 1);
}
}
===Link To Github page===
https://github.com/JimAlexBerger/MandelbrotProject
Why not move Renderer.CreateGraphics() outside of the loop? The memory leak is probably caused by redundantly calling Renderer.CreateGraphics() without calling IDisposable.Dispose() on the Graphics object.
double minR = System.Convert.ToDouble(MinR.Value);
double maxR = System.Convert.ToDouble(MaxR.Value);
double minI = System.Convert.ToDouble(MaxI.Value);
double maxI = System.Convert.ToDouble(MinI.Value);
int maxN = System.Convert.ToInt32(Iterations.Value);
SolidBrush MandelColor = new SolidBrush(Color.Red);
using(var graphics = Renderer.CreateGraphics())
{
graphics.Clear(Color.White);
for (int y = 0; y < Renderer.Height; y++)
{
for (int x = 0; x < Renderer.Width; x++)
{
double cr = fitInRRange(x, Renderer.Width, minR, maxR);
double ci = fitInIRange(y, Renderer.Height, minI, maxI);
int n = findMandelbrot(cr, ci, maxN);
double t = ((n + 0.0) / (maxN + 0.0));
MandelColor.Color = Color.FromArgb(System.Convert.ToInt32(9 * (1 - t) * t * t * t * 255), System.Convert.ToInt32(15 * (1 - t) * (1 - t) * t * t * 255), System.Convert.ToInt32(8.5 * (1 - t) * (1 - t) * (1 - t) * t * 255));
gfx.FillRectangle(MandelColor, x, y, 1, 1);
}
}
}
I'm trying to implement an N body simulation in C# using either Runge Kutta 4 or Velocity Verlet integration algorithms.
Before I move to a bigger number of particles, I wanted to test the simulation by modeling the earth's orbit around the sun, however, instead of the elliptical orbit, I get a weird spiral for some reason.
I can't figure out the problem since I made a simpler simulation of the solar system using the same algorithms where the sun was fixed in position and everything worked perfectly. The integrators work perfectly because it doesn't matter which one I use, I get the spiral with both.
Any help would be appreciated.
Here's the code:
class NBODY
{
public static double G = 4 * Math.PI * Math.PI;
class Particle
{
public double[] r; // position vector
public double[] v; // velocity vector
public double mass;
//constructor
public Particle() {}
public Particle(double x, double y, double z, double vx, double vy, double vz, double m)
{
this.r = new double[3];
this.v = new double[3];
this.r[0] = x;
this.r[1] = y;
this.r[2] = z;
this.v[0] = vx;
this.v[1] = vy;
this.v[2] = vz;
this.mass = m;
}
public void Update(Particle[] particles, double t, double h, int particleNumber)
{
RungeKutta4(particles, t, h, particleNumber);
}
private double acc(double r, Particle[] particles, int particleNumber, double[] r_temp, int l)
{
// dv/dt = f(x) = -G * m_i * (x - x_i) / [(x - x_i)^2 + (y - y_i)^2 + (z - z_i)^2]^(3/2)
double sum = 0;
switch (l)
{
case 0:
for (int i = 0; i < particles.Length; i++)
if (i != particleNumber)
sum += particles[i].mass * (r - particles[i].r[l]) / Math.Pow( Math.Pow(r - particles[i].r[l], 2)
+ Math.Pow(r_temp[1] - particles[i].r[1], 2) + Math.Pow(r_temp[2] - particles[i].r[2], 2), 1.5);
break;
case 1:
for (int i = 0; i < particles.Length; i++)
if (i != particleNumber)
sum += particles[i].mass * (r - particles[i].r[l]) / Math.Pow(Math.Pow(r - particles[i].r[l], 2)
+ Math.Pow(r_temp[0] - particles[i].r[0], 2) + Math.Pow(r_temp[2] - particles[i].r[2], 2), 1.5);
break;
case 2:
for (int i = 0; i < particles.Length; i++)
if (i != particleNumber)
sum += particles[i].mass * (r - particles[i].r[l]) / Math.Pow(Math.Pow(r - particles[i].r[l], 2)
+ Math.Pow(r_temp[0] - particles[i].r[0], 2) + Math.Pow(r_temp[1] - particles[i].r[1], 2), 1.5);
break;
}
return -G * sum;
}
private void RungeKutta4(Particle[] particles, double t, double h, int particleNumber)
{
//current position of the particle is saved in a vector
double[] r_temp = new double[3];
for (int j = 0; j < 3; j++)
r_temp[j] = this.r[j];
//loop going over all the coordinates and updating each using RK4 algorithm
for (int l = 0; l < 3; l++)
{
double[,] k = new double[4, 2];
k[0, 0] = this.v[l]; //k1_r
k[0, 1] = acc(this.r[l], particles, particleNumber, r_temp, l); //k1_v
k[1, 0] = this.v[l] + k[0, 1] * 0.5 * h; //k2_r
k[1, 1] = acc(this.r[l] + k[0, 0] * 0.5 * h, particles, particleNumber, r_temp, l); //k2_v
k[2, 0] = this.v[l] + k[1, 1] * 0.5 * h; //k3_r
k[2, 1] = acc(this.r[l] + k[1, 0] * 0.5 * h, particles, particleNumber, r_temp, l); //k3_v
k[3, 0] = this.v[l] + k[2, 1] * h; //k4_r
k[3, 1] = acc(this.r[l] + k[2, 0] * h, particles, particleNumber, r_temp, l); //k4_v
this.r[l] += (h / 6.0) * (k[0, 0] + 2 * k[1, 0] + 2 * k[2, 0] + k[3, 0]);
this.v[l] += (h / 6.0) * (k[0, 1] + 2 * k[1, 1] + 2 * k[2, 1] + k[3, 1]);
}
}
/*
Velocity Verlet algorithm:
1. Calculate y(t+h) = y(t) + v(t)h + 0.5a(t)h*h
2. Derive a(t+h) from dv/dt = -y using y(t+h)
3. Calculate v(t+h) = v(t) + 0.5*(a(t) + a(t+h))*h
*/
private void VelocityVerlet(Particle[] particles, double t, double h, int particleNumber)
{
double[] r_temp = new double[3];
for (int j = 0; j < 3; j++)
r_temp[j] = this.r[j];
//loop going over all the coordinates and updating each using RK4 algorithm
for (int l = 0; l < 3; l++)
{
//position
this.r[l] += h * this.v[l] + 0.5 * h * h * acc(this.r[l], particles, particleNumber, r_temp, l);
//velocity
this.v[l] += 0.5 * h * (acc(r_temp[l], particles, particleNumber, r_temp,l)
+ acc(this.r[l], particles, particleNumber, r_temp,l));
}
}
}
static void Main(string[] args)
{
//output file
TextWriter output = new StreamWriter("ispis.txt");
// declarations of variables
Particle[] particles = new Particle[2];
particles[0] = new Particle(0, 0, 0, 0, 0, 0, 1); //sun
particles[1] = new Particle(1, 0, 0, 0, 6.28, 0, 3.003467E-06); //earth
int N = 200;
double h, t, tmax;
double[,,] x = new double[particles.Length, N, 3]; //output
// setting initial values, step size and max time tmax
h = 0.01; // the step size in years
tmax = h * N;
// initial time
t = 0;
int i = 0;
while (t <= tmax) {
//updates position of all particles
for (int z = 1; z < particles.Length; z++)
particles[z].Update(particles, t, h, z);
//saves the position for output
for (int j = 1; j < particles.Length ; j++)
for (int z = 0; z < 3; z++ )
x[j,i,z] = particles[j].r[z];
t += h;
i++;
}
//output to file
for (int k = 0; k < particles.Length; k++ )
{
for (int f = 0; f < 3; f++)
{
for (int l = 0; l < N; l++)
output.Write(string.Format("{0,-15:0.########},", x[k,l,f]));
output.Write(string.Format("\n\n"));
}
output.Write(string.Format("\n\n\n\n"));
}
output.Close();
}
}
And here's the plot of the output data for earth's orbit:
Your model calculates the gravity force between two particles twice: for the first particle the force is based on their original coordinates, and for the second particle it is based on an updated position of the first one. This is a clear violation of the Newton's 3rd law. You must precompute all the forces before any update.
Your problem with the orbital of Earth is because the Center of Gravity of the System Earth-Sun, if you want to see the Orbital stay in loops you need to set center Of Gravity In (x,y,z)=(0,0,0) ;
I have a C# code based on your code Above so :
public partial class Form1 : Form
{
static
int
x1,y1,x2,y2, x3, y3;//for the 3th particule
private void timer1_Tick_1(object sender, EventArgs e)
{Moveu();
Invalidate();
}
private void button1_Click_1(object sender, EventArgs e)
{
timer1.Enabled = !timer1.Enabled;
}
public Form1()
{
InitializeComponent();
Paint += new PaintEventHandler(paint);
MouseDown += new MouseEventHandler(mouse_Click);
MouseUp += new MouseEventHandler(mouse_up);
MouseMove += new MouseEventHandler(mouse_move);
// x y z vx vy vz m
particles[0] = new Particle( 0, 0, 0, 0, 0, 0, 1 ) ; //sun
particles[1] = new Particle( 1, 0, 0, 0, 6, 0, 0.03 ); //earth
// particles[2] = new Particle( 0, 2, 0, 0, 0, 0, 1 ); //planet
x1 = (int)(100 * particles[0].r[0] + 300);
y1 = (int)(100 * particles[0].r[1] + 300);
x2 = (int)(100 * particles[1].r[0] + 300);
y2 = (int)(100 * particles[1].r[1] + 300);
}
Particle[] particles = new Particle[2];
void Moveu()
{
double h, t;
// setting initial values, step size and max time tmax
h = 0.005; // the step size in years
// initial time
t = 0;
//updates position of --all-- particles ( z=0 not z=1 )
for (int z = 0; z < particles.Length; z++)
particles[z].RungeKutta4(particles, t, h, z);
x1 = (int)(100 * particles[0].r[0] + 300); // +300 just for render it in centre
y1 = (int)(100 * particles[0].r[1] + 300);
x2 = (int)(100 * particles[1].r[0] + 300);
y2 = (int)(100 * particles[1].r[1] + 300);
// x3 = (int)(100 * particles[2].r[0] + 300);
// y3 = (int)(100 * particles[2].r[1] + 300);
}
void paint(object s, PaintEventArgs e)
{
Graphics graf;
graf = CreateGraphics();
graf.FillEllipse(new SolidBrush(Color.AntiqueWhite), x1 + move.X, y1 + move.Y, 50, 50);
graf.FillEllipse(new SolidBrush(Color.Blue), x2 + move.X, y2 + move.Y, 10, 10);
// graf.FillEllipse(new SolidBrush(Color.Yellow), x3, y3, 20, 20);
}
class Particle
{
public double[] r; // position vector
public double[] v; // velocity vector
public double mass;
//constructor
public Particle() { }
public Particle(double x, double y, double z, double vx, double vy, double vz, double m)
{
this.r = new double[3];
this.v = new double[3];
this.r[0] = x;
this.r[1] = y;
this.r[2] = z;
this.v[0] = vx;
this.v[1] = vy;
this.v[2] = vz;
this.mass = m;
}
private double acc(double r, Particle[] particles, int particleNumber, double[] r_temp, int l)
{
// dv/dt = f(x) = -G * m_i * (x - x_i) / [(x - x_i)^2 + (y - y_i)^2 + (z - z_i)^2]^(3/2)
double sum = 0;
switch (l)
{
case 0:
for (int i = 0; i < particles.Length; i++)
if (i != particleNumber)
sum += particles[i].mass * (r - particles[i].r[l]) / Math.Pow(Math.Pow(r - particles[i].r[l], 2)
+ Math.Pow(r_temp[1] - particles[i].r[1], 2) + Math.Pow(r_temp[2] - particles[i].r[2], 2), 1.5);
break;
case 1:
for (int i = 0; i < particles.Length; i++)
if (i != particleNumber)
sum += particles[i].mass * (r - particles[i].r[l]) / Math.Pow(Math.Pow(r - particles[i].r[l], 2)
+ Math.Pow(r_temp[0] - particles[i].r[0], 2) + Math.Pow(r_temp[2] - particles[i].r[2], 2), 1.5);
break;
case 2:
for (int i = 0; i < particles.Length; i++)
if (i != particleNumber)
sum += particles[i].mass * (r - particles[i].r[l]) / Math.Pow(Math.Pow(r - particles[i].r[l], 2)
+ Math.Pow(r_temp[0] - particles[i].r[0], 2) + Math.Pow(r_temp[1] - particles[i].r[1], 2), 1.5);
break;
}
return -G * sum;
}
public void RungeKutta4(Particle[] particles, double t, double h, int particleNumber)
{
//current position of the particle is saved in a vector
double[] r_temp = new double[3];
for (int j = 0; j < 3; j++)
r_temp[j] = this.r[j];
//loop going over all the coordinates and updating each using RK4 algorithm
for (int l = 0; l < 3; l++)
{
double[,] k = new double[4, 2];
k[0, 0] = this.v[l]; //k1_r
k[0, 1] = acc(this.r[l], particles, particleNumber, r_temp, l); //k1_v
k[1, 0] = this.v[l] + k[0, 1] * 0.5 * h; //k2_r
k[1, 1] = acc(this.r[l] + k[0, 0] * 0.5 * h, particles, particleNumber, r_temp, l); //k2_v
k[2, 0] = this.v[l] + k[1, 1] * 0.5 * h; //k3_r
k[2, 1] = acc(this.r[l] + k[1, 0] * 0.5 * h, particles, particleNumber, r_temp, l); //k3_v
k[3, 0] = this.v[l] + k[2, 1] * h; //k4_r
k[3, 1] = acc(this.r[l] + k[2, 0] * h, particles, particleNumber, r_temp, l); //k4_v
this.r[l] += (h / 6.0) * (k[0, 0] + 2 * k[1, 0] + 2 * k[2, 0] + k[3, 0]);
this.v[l] += (h / 6.0) * (k[0, 1] + 2 * k[1, 1] + 2 * k[2, 1] + k[3, 1]);
}
}
}
public static double G = 4 * Math.PI * Math.PI; //then time unite in years and length unite = distance between Earth and Sun and masse is the sun masse unite
void mouse_Click(object o, MouseEventArgs e)
{
dwn = new Point(e.X, e.Y);
if ("" + e.Button == "Left")
{
pos = move;
clicked = true;
}
}
void mouse_move(object o, MouseEventArgs e)
{
if (clicked)
{
move = new Point(e.X + pos.X - dwn.X, e.Y + pos.Y - dwn.Y);
Invalidate();
}
}
void mouse_up(object o, MouseEventArgs e)
{
clicked = false;
}
Point dwn, pos,move;
bool clicked;
}`you need to create a Timer and a button [![enter image description here][1]][1]