bool searchMatrix(vector<vector<int>>& matrix, int target) { int i = 0; int j = matrix[0].size()-1; while(i < matrix.size() && j >= 0){ if(matrix[i][j] == target) return true; if(matrix[i][j] > target) j--; else i++; } return false; }
static void Main() { double a = 0; // boundary condition vector ya = new vector(0, 1); // initial function values double b = 2 * PI; // "end" value double h = 1; // step size double acc = 1e-3; // precision (used in "approx") double eps = 1e-3; // precision (used in "approx") var xs = new List <double>(); // x-values (to be filled) var ys = new List <vector>(); // y-values (to be filled) vector y = ode.rk45(F, a, ya, b, acc: acc, eps: eps, h: h, xlist: xs, ylist: ys); // solving the ODE /* Printing output to "Log" */ Error.WriteLine($"acc={acc} eps={eps}"); Error.WriteLine($"npoints={xs.Count}"); Error.WriteLine($"a={a} y0({a})={ya[0]} y1({a})={ya[1]}"); Error.WriteLine($"b={b}"); Error.WriteLine($"y0 (b)={y[0]} y1(b)={y[1]}"); Error.WriteLine($"sin(b)={Sin(b):f15} cos(b)={Cos(b):f15}"); /* Test to see if the precision of our Runge-Kutta solution satisfies the true solution within the required precision */ if (approx(y[0], Sin(b), acc, eps) && approx(y[1], Cos(b), acc, eps)) { Error.WriteLine("test passed"); } else { Error.WriteLine("test failed"); } for (int i = 0; i < xs.Count; i += 900) { // for(int i=0;i<xs.Count;i+=10) WriteLine($"{xs[i]} {ys[i][0]} {ys[i][1]}"); } }
private void xuanranshow(Graphics g) { try { vector pVector = new vector(); SolidBrush brush = null; //this.vo.ShowDialog(); rayvector pFrmRayVector = new rayvector(); // 模态窗口 if (pFrmRayVector.ShowDialog() == DialogResult.OK) { pVector = pFrmRayVector.GetRayvector(); } //用于存储网格向量 vec = new vector[Convert.ToInt32(dem.RowsNum), Convert.ToInt32(dem.ColsNum)]; vec = Gp.brightness(dem.ElementData, dem.Cellsize, Convert.ToInt32(dem.RowsNum), Convert.ToInt32(dem.ColsNum)); //用于存储所有的角度 double[,] anger = new double[Convert.ToInt32(dem.RowsNum), Convert.ToInt32(dem.ColsNum)]; anger = Gp.d_raytovector_angle_all(vec, Convert.ToInt32(dem.RowsNum), Convert.ToInt32(dem.ColsNum), pVector); //用来存放所有的灰度值 double[,] huidu = new double[Convert.ToInt32(dem.RowsNum), Convert.ToInt32(dem.ColsNum)]; huidu = Gp.i_cellvalue_hillshade(anger, Convert.ToInt32(dem.RowsNum), Convert.ToInt32(dem.ColsNum)); for (int i = 0; i < dem.ColsNum; i++) { for (int j = 0; j < dem.RowsNum; j++) { Rectangle rect = new Rectangle(i * this.dem.Cellsize, j * this.dem.Cellsize, this.dem.Cellsize, this.dem.Cellsize);//定义一个方形的大小 brush = new SolidBrush(Color.FromArgb((int)huidu[i, j], Color.Black)); g.FillRectangle(brush, rect); } } } catch (System.Exception ex) { MessageBox.Show("数组为空"); } }
static void Main(string[] args) { // PLAIN SAMPLING writetitle("\nPlain sampling"); Func <vector, double> f = (x) => Sin(x[0]) / x[0]; vector a = new vector(0.0), b = new vector(PI); int N = (int)1e4; double exp = 1.852; // expected (double res, _) = mcint.plainmc(f, a, b, N); // result WriteLine(string.Format("{0, -28} {1, -8} {2, -8} {3, -8} {4, -8}", "function", "a", "b", "expected", "result")); WriteLine($"{"Sin(x)/x", -28} {0, -8} {PI, -8:F3} {exp, -8:F3} {res, -8:F3}"); f = (x) => Pow(PI * PI * PI * (1 - Cos(x[0]) * Cos(x[1]) * Cos(x[2])), -1); a = new vector(0, 0, 0); b = new vector(PI, PI, PI); N = (int)1e5; exp = 1.392; (res, _) = mcint.plainmc(f, a, b, N); WriteLine($"{"(pi³(1-cosx*cosy*cosz))⁻¹", -28} {0, -8} {PI, -8:F3} {exp, -8:F3} {res, -8:F3}"); // STRATIFIED SAMPLING writetitle("\nRecursive stratified sampling"); N = (int)1e4; exp = 1.852; // expected (res, _) = mcint.stratified(f, a, b, N); // result WriteLine(string.Format("{0, -28} {1, -8} {2, -8} {3, -8} {4, -8}", "function", "a", "b", "expected", "result")); WriteLine($"{"Sin(x)/x", -28} {0, -8} {PI, -8:F3} {exp, -8:F3} {res, -8:F3}"); f = (x) => Pow(PI * PI * PI * (1 - Cos(x[0]) * Cos(x[1]) * Cos(x[2])), -1); a = new vector(0, 0, 0); b = new vector(PI, PI, PI); N = (int)1e5; exp = 1.392; (res, _) = mcint.stratified(f, a, b, N); WriteLine($"{"(pi³(1-cosx*cosy*cosz))⁻¹", -28} {0, -8} {PI, -8:F3} {exp, -8:F3} {res, -8:F3}"); }
internal bool addBud(RoadBud bud, short x, short y, Direction dir) { PointS at = PointS.pointFrom(x, y, dir, 1); if (!world.isInWorld(at.x, at.y)) { return(false); } Voxel toward = world[at.x, at.y]; if (toward.road != null && toward.road.getLevel(dir) <= bud.level) { return(false); } vector key = new vector(x, y, dir); if (buds.ContainsKey(key)) { buds.Remove(key); } buds.Add(key, bud); Debug.WriteLine("new bud at:(" + x + "," + y + ") to " + dir); return(true); }
public static vector newton (Func <vector, vector> f, vector x, double eps = 1e-3, double dx = 1e-7) { int n = x.size; vector fx = f(x), z, fz; while (true) { matrix J = jacobian(f, x, fx); qrdecomposition qrJ = new qrdecomposition(J); matrix B = qrJ.inverse(); vector Dx = -B * fx; double s = 1; while (true) // backtracking linesearch { z = x + Dx * s; fz = f(z); if (fz.norm() < (1 - s / 2) * fx.norm()) { break; } if (s < 1.0 / 32) { break; } s /= 2; } x = z; fx = fz; if (fx.norm() < eps) { break; } } return(x); } //broyden
public void handleColisions() { PhysicsObject[] AllObjects = FindObjectsOfType <PhysicsObject>(); for (int i = 0; i < AllObjects.Length; i++) { for (int j = i + 1; j < AllObjects.Length; j++) { Debug.Log("testing"); IntersectData intersectdata = AllObjects[i].col.intersect(AllObjects[j].col); if (intersectdata.DoesIntersect) { Debug.Log("intersection"); vector direction = intersectdata.distance.normalized; vector otherdirection = vector.reflect(direction, AllObjects[i].vel).normalized; AllObjects[i].vel = vector.reflect(AllObjects[i].vel, otherdirection); AllObjects[j].vel = vector.reflect(AllObjects[j].vel, direction); Debug.Log("intersection done"); } } } }
static void Main() { System.IO.StreamReader inputfile = new System.IO.StreamReader("higgs_data.data"); string s = inputfile.ReadLine(); while (!(s == null)) { string[] values = s.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); energy.Add(double.Parse(values[0])); crossSection.Add(double.Parse(values[1])); error.Add(double.Parse(values[2])); s = inputfile.ReadLine(); } double epsilon = 1e-7; vector param = new vector(120, 4.83, 20); int num_of_steps = qnewton(chiSquared, ref param, epsilon); WriteLine("\n__________________________________________________________________________________________________________"); WriteLine("Question A\n Higgs discovery"); WriteLine("Fit of higgs mass:"); WriteLine("m = {0}, Γ = {1}, A = {2}", param[0], param[1], param[2]); WriteLine("Expected mass: {0}", 125.3); WriteLine("Number of steps : {0}", num_of_steps); WriteLine("See fit in PlotB.svg"); WriteLine("__________________________________________________________________________________________________________\n"); System.IO.StreamWriter outputfile = new System.IO.StreamWriter("out.fitfun.txt", append: false); vector Es = linspace(101, 159, 400); for (int i = 0; i < 400; i++) { outputfile.WriteLine("{0} {1}", Es[i], breit_wigner(param, Es[i])); } outputfile.Close(); }
public static int Main() { // Using a gaussian function, since the integral from -infty to infty is sqrt(pi) Func <double, double> g = delegate(double x){ return(Exp(-x * x)); }; vector g1 = integrator.recint_inf(g, Double.NegativeInfinity, Double.PositiveInfinity); vector g2 = integrator.recint_inf(g, 0, Double.PositiveInfinity); vector g3 = integrator.recint_inf(g, 0, Double.NegativeInfinity); Write($"The result, which should be {Sqrt(PI)} gave {g1[0]}+-{g1[1]} in {g1[2]} iterations\n"); Write($"The result, which should be {Sqrt(PI)/2} gave {g2[0]}+-{g2[1]} in {g2[2]} iterations\n"); Write($"The result, which should be {-Sqrt(PI)/2} gave {g3[0]}+-{g3[1]} in {g3[2]} iterations\n"); double o1 = integrator.o8av(g, Double.NegativeInfinity, Double.PositiveInfinity); double o2 = integrator.o8av(g, 0, Double.PositiveInfinity); double o3 = -integrator.o8av(g, Double.NegativeInfinity, 0); Write($"The values returned for the same 3 integrals by o8av are\n{o1}\n{o2}\n{o3}\n Although the integral from 0-> NegInfty had to be manually rearranged for o8av\n"); return(0); }
public OrdLeastSquares(vector x, vector y, vector dy, Func <double, double>[] fs) { int n = y.size; int m = fs.Length; matrix A = new matrix(n, m); vector b = new vector(n); // Creating the matrix and vector going into QRdecomp. for (int i = 0; i < n; i = i + 1) { b[i] = y[i] / dy[i]; for (int j = 0; j < m; j = j + 1) { A[i, j] = fs[j](x[i]) / dy[i]; } } // Matrix and vector ready for QRdecomp QRdecompositionGS QRdecomp = new QRdecompositionGS(A); c = QRdecomp.solve(b); matrix sigmainv = QRdecomp.R.transpose() * QRdecomp.R; QRdecompositionGS cov = new QRdecompositionGS(sigmainv); sigma = cov.inverse(); }
} //end randomx... public static vector plainmc(Func <vector, double> f, vector a, vector b, int N) { //the volume is calculated as: double vol = 1; for (int i = 0; i < a.size; i++) { vol = vol * (b[i] - a[i]); } //end for //something else: var rand = new Random(); Func <vector> randomx1 = delegate() { vector x = new vector(a.size); for (int i = 0; i < x.size; i++) { x[i] = a[i] + rand.NextDouble() * (b[i] - a[i]); } //end for return(x); }; //end func.. double sum = 0; double sum2 = 0; // sums... //sampling the integration area N times: for (int i = 0; i < N; i++) { vector v = randomx1(); // sampel sum = sum + f(v); sum2 = sum2 + f(v) * f(v); //updating sums } // end for double mean = sum / N; //mean value double SIGMA = Sqrt(sum2 / N - mean * mean) / Sqrt(N); //the an estimate for the error return(new vector(mean * vol, SIGMA * vol)); } //end plainmc
public static vector plainmc(Func <vector, double> f, vector a, vector b, int N) { double volume = 1; // Total volume for (int i = 0; i < a.size; i++) { volume *= b[i] - a[i]; } double sum = 0; double sum2 = 0; for (int i = 0; i < N; i++) { double fx = f(randomx(a, b)); sum += fx; sum2 += fx * fx; } double mean = sum / N; // <f_i> double sigma = Sqrt(sum2 / N - mean * mean); // sigma² = <(f_i)²> - <f_i>² double SIGMA = sigma / Sqrt(N); // SIGMA² = <Q²> - <Q>² return(new vector(mean * volume, volume * SIGMA)); }
public static Result mc_plain(Func <vector, double> func, vector a, vector b, int N) { double volume = 1; for (int i = 0; i < a.size; i++) { volume *= b[i] - a[i]; } double sum = 0; double sum2 = 0; for (int i = 0; i < N; i++) { var fx = func(randomx(a, b)); sum += fx; sum2 += fx * fx; } double mean = sum / N; double sigma = Sqrt(sum2 / N - mean * mean); double res_sigma = sigma / Sqrt(N); var res = new Result(mean * volume, res_sigma * volume); return(res); }
public void train(vector x, vector y) { double res1 = 0; Func <vector, double> deltaP = (k) => { p = k; double res = 0; for (int i = 0; i < x.size; i++) { res += Pow((feedforward(x[i]) - y[i]), 2); } res1 = res; return(res); }; vector pa = p.copy(); int ncounts = Quasi.qnewton(deltaP, ref pa); p = pa; double TH = 0.01; //threshhold if (res1 > TH) { calls++; res1 = 0; for (int i = 0; i < 3 * n; i++) { double u1 = 1.0 - rand.NextDouble(); double u2 = 1.0 - rand.NextDouble(); p[i] = Math.Sqrt(-2.0 * Math.Log(u1)) * Math.Sin(2.0 * Math.PI * u2); } train(x, y); } }
static int Main(string[] args) { double xa = 0; double xb = 3; vector ya = new vector(0.5); List <double> xs = new List <double>(); List <vector> ys = new List <vector>(); Func <double, vector, vector> ydiff = delegate(double x, vector y){ var res = new vector(y[0] * (1 - y[0])); return(res); }; vector yb = ode.rk23(ydiff, xa, ya, xb, xs, ys); double logistic = 0; for (int i = 0; i < xs.Count; i++) { logistic = 1 / (1 + Exp(-xs[i])); WriteLine($"{xs[i]} {ys[i][0]} {logistic}"); } return(0); }
} // end constructor public int training(vector xs, vector ys, double eps = 1e-3) { // Create a vector with initial parameters, that spread out activation functions // somewhat evenly. // We set the a_i's to evenly span the distance from [c, d] where c and d are the // start and end-point of the interval along the x-axis, that we are interested in. // I assume that the training data is provided in order, with the first point being at // c and the last at d vector param = new vector(3 * n); for (int i = 0; i < n; i++) { param[0 + 3 * i] = xs[0] + (xs[xs.size - 1] - xs[0]) * i / (n - 1); param[1 + 3 * i] = 1; // b_i's start at 1 param[2 + 3 * i] = 1; // Weights start at 1 } Func <vector, double> deviation = delegate(vector p){ double sum = 0; // Go through the data points, and calculate the total deviation for (int i = 0; i < xs.size; i++) { sum += Pow((feedforward(xs[i], p) - ys[i]), 2); } return(sum); }; // Perform the optimization int nsteps = minimization.qnewton(deviation, ref param, eps); // The vector param now contains the optimized parameters, so we now save this in // the finalParams vector that is available to all functions and outside the class finalParams = param; return(nsteps); } // end training
public static vector newton(Func <vector, vector> f, vector x, double eps = 1e-3, double dx = 1e-7) { vector fx = f(x); matrix J = jacobian(f, x, dx); matrix R = new matrix(J.size2, J.size2); gs.decomp(J, R); matrix B = gs.inverse(J, R); vector Dx = -B *f(x); vector root; //WriteLine(x[0]); //WriteLine(fx.norm()); double lambda = 1.0; while ((f(x + lambda * Dx)).norm() > (1 - lambda / 2) * fx.norm() && (lambda > 1.0 / 64)) { lambda /= 2; } x = x + lambda * Dx; if (Dx.norm() < dx) { root = x; } else if (f(x).norm() < eps) { root = x; } else { root = newton(f, x, eps, dx); } return(root); }
public static void Main(string[] args) { vector x = new vector(0, 1, 2, 3); vector y = new vector(0, 2, 4, 6); vector siny = new vector(x.size); for (int i = 0; i < x.size; i++) { siny[i] = Sin(x[i]); } WriteLine(string.Format("# {0, -8} {1, -10} {2, -10} {3, -10} {4, -10}, {5, -10}", "x", "y", "integral", "sin(x)", "integral", "exactint")); double z; double steps = 4; // interpolates 4 steps between points for (int i = 0; i < x.size - 1; i++) { for (int j = 0; j < steps; j++) { z = x[i] + (x[i + 1] - x[i]) * j / steps; WriteLine($"{z, -10:F3} {interpolate.linear.spline(x, y, z), -10:F3} {interpolate.linear.integrate(x, y, z), -10:F3} {interpolate.linear.spline(x, siny, z), -10:F3} {interpolate.linear.integrate(x, siny, z), -10:F3} {-Cos(z) + 1, -10:F3}"); } } }
public static int Main(string[] args) { // Require exactly 1 input parameter if (args.Length != 1) { return(1); } // The input parameter is the dimension of the matrix int n = int.Parse(args[0]); // We start out by creating a random symmetric matrix. var rand = new Random(); // We can pull out new random numbers between 0 and 1 with rand.NextDouble() and // stuff it into a matrix matrix A = new matrix(n, n); for (int i = 0; i < n; i++) { A[i, i] = 2 - 4 * rand.NextDouble(); for (int j = i + 1; j < n; j++) { A[i, j] = 2 - 4 * rand.NextDouble(); A[j, i] = A[i, j]; } } // Perform a cyclic sweep on the matrix A matrix V = new matrix(n, n); vector e = new vector(n); jacobi.cycle(A, e, V); return(0); }
public static void Main() { // y[0] = y // y[1] = y' // y'[1] = -y[0] // y'[0] = y[1] // y'(x) = y(x) * (1 - y(x)) Func <double, vector, vector> f = delegate(double x, vector y){ return(new vector(y[0] * (1 - y[0]), 0)); }; int xa = 0; int xb = 3; vector ya = new vector(0.5, 0); List <double> xs = new List <double>(); List <vector> ys = new List <vector>(); ode.rk23(f, xa, ya, xb, xlist: xs, ylist: ys); List <double> expected = xs.Select(x => 1 / (1 + Exp(-x))).ToList(); for (int i = 0; i < xs.Count; i++) { WriteLine($"{xs[i]} {ys[i][0]} {expected[i]}"); } }
public static int Main() { double eps = 1e-3; energy = new System.Collections.Generic.List <double>(); sigma = new System.Collections.Generic.List <double>(); error = new System.Collections.Generic.List <double>(); System.IO.StreamReader data = new System.IO.StreamReader("higgs_data.txt"); do { string s = data.ReadLine(); if (s == null) { break; } char[] sep = new char[] { ' ' }; string[] splitted = s.Split(sep, StringSplitOptions.RemoveEmptyEntries); energy.Add(double.Parse(splitted[0])); sigma.Add(double.Parse(splitted[1])); error.Add(double.Parse(splitted[2])); } while (true); vector parameters = new vector(new double [] { 125.0, 4.0, 5 }); var fit = minimization.qnewton(D, ref parameters, eps); WriteLine($"Parameters from fit: mass, m = {parameters[0]}, widths of resonance, gamma = {parameters[1]}, and scale factor, A = {parameters[2]}"); WriteLine($"Computed with {fit} steps."); for (double e = energy[0]; e <= energy[energy.Count - 1]; e += 1.0 / 10) { Error.WriteLine("{0} {1}", e, parameters[2] * breitWigner(parameters[0], parameters[1], e)); } return(0); }
static int Main(string[] args) { int N; if (args.Length > 0) { N = int.Parse(args[0]); } else { N = 3; } int nm = N; matrix A1 = randmatrix_sym(nm, nm); matrix V = new matrix(nm, nm); int nr = 0; vector e = jac_dia_red(A1, V, 1, ref nr); WriteLine($" {nr}"); return(0); }
public static (vector, matrix, int) cyclic(matrix A) { rotations = 0; int n = A.size1; matrix V = new matrix(n, n); // eigenvectors vector e = new vector(n); // eigenvalues for (int i = 0; i < n; i++) { V[i, i] = 1; // initialized to I } bool change = true; while (change) { for (int i = 0; i < n; i++) { e[i] = A[i, i]; // update eigenvalues } sweep(A, V); // perform a sweep change = changed(A, e); // check if the eigenvalues were actually changed in this iteration } return(e, V, rotations); }
return int_sum; } //method:feed_int public void train(double[] xs, double[] ys){ int calls=0; Error.WriteLine("STARTING TRAINING"); Func<vector,double> diviation = (u) =>{ calls++; parameters=u; double diviation_sum=0; for(int i=0;i<xs.Length;i++){ diviation_sum+=(ys[i]-feed(xs[i]))*(ys[i]-feed(xs[i])); } Error.WriteLine($"Diviation = {diviation_sum/xs.Length}"); return diviation_sum/xs.Length; };//func:diviation vector v=parameters; parameters=qnewton.sr1(diviation,v,1e-6); Error.WriteLine($"calls={calls}"); } //method:train
// This constructor reads a two column file, 1st column is xs, second is // ys, and calculates the dys as errorFunc(ys); public data(string filename) { var reader = new System.IO.StreamReader(filename); int fileLength = 0; while (reader.ReadLine() != null) { fileLength += 1; } reader.Close(); xs = new vector(fileLength); ys = new vector(fileLength); sigma_ys = new vector(fileLength); reader = new System.IO.StreamReader(filename); for (int i = 0; i < xs.size; i++) { string line = reader.ReadLine(); // Error.Write($"Read line: \"{line}\"\n"); string[] words = line.Split(' '); xs[i] = double.Parse(words[0]); ys[i] = double.Parse(words[1]); sigma_ys[i] = double.Parse(words[2]); } }
static void Main() { Write("Problem B:\n"); Write("See B.sigmaNDependence.svg\n"); // Now for Dimitris function: /* * Func<vector, double> f = (v) => * 1/(1-Cos(v[0])*Cos(v[1])*Cos(v[2]))*1/(PI*PI*PI); * vector a = new vector(0.0, 0.0, 0.0); * vector b = new vector(PI, PI, PI); * double expectedRes = 1.3932039296856768591842462603255; */ Func <vector, double> f = (v) => Sin(v[0]) * Sin(v[0]); vector a = new vector(0.0); vector b = new vector(2 * PI); double expectedRes = PI; // Make data file: var outfile = new System.IO.StreamWriter("out.dataB.txt"); int Nmin = 1000; int Nmax = 50000; int Nstep = (Nmax - Nmin) / 100; vector intResult0 = mcIntegrator.plainmc(f, a, b, Nmax); Func <double, double> simpleFit = (N) => intResult0[1] * Sqrt(Nmax) / Sqrt(N); for (int N = Nmin; N <= Nmax; N += Nstep) { vector intResult = mcIntegrator.plainmc(f, a, b, N); outfile.Write("{0} {1} {2} {3}\n", N, intResult[1], Abs(intResult[0] - expectedRes), simpleFit(N)); } outfile.Close(); }
static int Main(string[] args) { // input to vector... var input = new System.IO.StreamReader("sin_data.txt"); int input_lenght = 0; while (input.ReadLine() != null) { input_lenght++; } input.Close(); input = new System.IO.StreamReader("sin_data.txt"); vector x1 = new vector(input_lenght); vector y1 = new vector(input_lenght); string line; for (int n = 0; n < input_lenght; n++) { line = input.ReadLine(); string[] words = line.Split(' '); x1[n] = double.Parse(words[0]); y1[n] = double.Parse(words[1]); } //end input to vector... cspline a = new cspline(x1, y1); for (double n = 0; n <= 10; n += 0.05) { WriteLine($"{n} {a.c_spline(n)}"); } return(0); }
private void Fire() { if (this.Energy > ShipParameters.MinEnergyToFire) { this.Energy -= ShipParameters.EnergyToFire; var orthogonalDirection = Direction.FromRadian(Heading.InRadians + radian.FromDegree(-90)); var rightInFront = new WrappingLocation(this.Location, Heading, new Distance(2000.0d)); var bitLeft = new WrappingLocation(rightInFront, orthogonalDirection, new Distance(1000.0d)); var bitRight = new WrappingLocation(rightInFront, orthogonalDirection, new Distance(-1000.0d)); var fireVector = new vector(Heading, ShipParameters.BulletVelocity); var bulletVector = this.Movement + fireVector; var bulletLeft = new Bullet(bitLeft, bulletVector, ShipParameters.BulletSize, ShipParameters.BulletDamage, ShipParameters.BulletLifetime); var bulletRight = new Bullet(bitRight, bulletVector, ShipParameters.BulletSize, ShipParameters.BulletDamage, ShipParameters.BulletLifetime); bulletLeft.Update(); bulletRight.Update(); Game.Subscribe(bulletLeft); Game.Subscribe(bulletRight); } }
public static vector Gradient(Func <vector, double> f, vector x) // Input function with vector as arguments { vector Gradient = new vector(x.size); vector dx = new vector(x.size); double δx; double Ɛ = 1.0 / 4194304; // for (int i = 0; i < x.size; i = i + 1) { if (Abs(x[i]) < Sqrt(Ɛ)) { δx = Ɛ; } else { δx = Abs(x[i]) * Ɛ; } dx[i] = δx; Gradient[i] = (f(x + dx) - f(x)) / δx; dx[i] = dx[i] - δx; } return(Gradient); }
public static void Main() { Write("==== A.1 ====\n"); Write("Testing on random tall matrix A:\n"); matrix a = rndMat.randomMatrix(5, 3); a.print("A ="); qrDecompositionGS qr = new qrDecompositionGS(a); Write("Q and R matrices found from QR-factorization:\n"); (qr.q).print("Q = ");; (qr.r).print("R = ");; Write("Testing that Q is orthogonal:\n"); (qr.q.transpose() * qr.q).print("Q^T*Q = "); Write("Calculating the difference between A and QR, which should be 0:\n"); (a - qr.q * qr.r).print("A-QR = "); Write("\n==== A.2 ====\n"); Write("Testing solver on random matrix A:\n"); a = rndMat.randomMatrix(5, 5); a.print("A = "); qr = new qrDecompositionGS(a); Write("and random vector b:\n"); vector b = rndMat.randomVector(5); b.print("b = "); Write("Solution to Ax=b is found to be:\n"); vector x = qr.solve(b); x.print("x = "); Write("Checking that x is a solution by calculating 0=Ax-b:\n"); vector diff = a * x - b; diff.print("A*x-b = "); } //Main
public static int Main() { int n = 6; double x1 = 0, xend = 2 * PI; vector xs = new vector(n); vector ys = new vector(n); System.IO.StreamWriter outputfile = new System.IO.StreamWriter("out-xydata.txt", append: false); for (int i = 0; i < n; i++) { xs[i] = x1 + (xend - x1) / (n - 1) * i; ys[i] = Sin(xs[i]); outputfile.WriteLine("{0} {1}", xs[i], ys[i]); } outputfile.Close(); int N = 2000; double z = 0; double z1 = x1; double zend = xend; System.IO.StreamWriter outputfileSpline = new System.IO.StreamWriter("out-linterp.txt", append: false); System.IO.StreamWriter outputfileIntegral = new System.IO.StreamWriter("out-integral.txt", append: false); for (int i = 0; i < N; i++) { z = z1 + (zend - z1) / (N - 1) * i; outputfileSpline.WriteLine("{0} {1} {2}", z, linspline.linterp(xs, ys, z), Sin(z)); outputfileIntegral.WriteLine("{0} {1} {2}", z, linspline.linterpInteg(xs, ys, z), 1 - Cos(z)); } outputfileSpline.Close(); outputfileIntegral.Close(); return(0); }
public static vector operator ^(matrix a, vector x) { vector y = new vector(a.cols); for(int i=0;i<a.cols;i++){ y[i]=0; for(int k=0;k<a.rows;k++) y[i]+=a[k,i]*x[k]; } return y; }
public static vector operator *(matrix a, vector x) { vector y = new vector(x.size); for(int i=0;i<x.size;i++){ y[i]=0; for(int ac=a.cols,k=0;k<ac;k++) y[i]+=a[i,k]*x[k]; } return y; }
public vector col(int i) { // get{ vector v = new vector(); v.size=nrows; v.first=i*nrows; v.data=data; return v; // } // set{for(int k=0;k<nrows;k++)data[k+i*nrows]=value[k];} }
string minMultiples(int N, vector <int> forbiddenDigits);
public vector this[int i] { get{ vector v = new vector(); v.size=nrows; v.first=i*nrows; v.data=data; return v; } set{for(int k=0;k<nrows;k++) data[k+i*nrows]=value[k];} }
Bitmap render_layer(TreeNode layer_node, int height, int width, int centerX, int centerY, wz_file f, image map_img) { TreeNode t_node, t_node2; int x = 0, y = 0, z = 0, i = 0; vector v = new vector(0, 0); bool flipped = false; SortedList<int, List<tile>> z_layer_objects = new SortedList<int, List<tile>>(); SortedList<int, List<tile>> z_layer_tiles = new SortedList<int, List<tile>>(); Bitmap bMap = new Bitmap(width, height); Graphics gMap = Graphics.FromImage(bMap); image tile_img, obj_img; string tS_tile = ""; TreeNode found_node; toolStripStatusLabel1.Text = "Getting Objects..."; t_node = FindNode(layer_node, "obj"); for (i = 0; i < t_node.Nodes.Count; i++) { t_node2 = FindNode(t_node, i.ToString()); if (t_node2 != null) { found_node = FindNode(t_node2, "x"); if (found_node != null) { x = (int)found_node.Tag; } found_node = FindNode(t_node2, "y"); if (found_node != null) { y = (int)found_node.Tag; } found_node = FindNode(t_node2, "z"); if (found_node != null) { z = (int)found_node.Tag; } found_node = FindNode(t_node2, "f"); if (found_node != null) { flipped = System.Convert.ToBoolean(found_node.Tag); } string oS_obj = (string)(FindNode(t_node2, "oS").Tag); string l0_obj = (string)(FindNode(t_node2, "l0").Tag); string l1_obj = (string)(FindNode(t_node2, "l1").Tag); string l2_obj = (string)(FindNode(t_node2, "l2").Tag); obj_img = FindImage("Map\\Obj\\" + oS_obj + ".img",treeView1.Nodes[0]); object png_uol = get_value(l0_obj + "\\" + l1_obj + "\\" + l2_obj + "\\0", obj_img); PNG png; if (png_uol.GetType().Name == "UOL") { MessageBox.Show("UOL obj"); TreeNode uol_node = FindNode(FindNode(FindNode(FindNode(obj_img.node, l0_obj), l1_obj), l2_obj), "0"); png = (PNG)resolve_UOL((UOL)png_uol, uol_node).Tag; } else { png = (PNG)png_uol; } found_node = FindByFullPath(l0_obj + "\\" + l1_obj + "\\" + l2_obj + "\\0", obj_img.node); found_node = FindNode(found_node, "origin"); if (found_node != null) { v = (vector)found_node.Tag; } if (z_layer_objects.ContainsKey(z)) { z_layer_objects[z].Add(new tile(extract_png(png, f), x, y, v.x, v.y, flipped)); } else { z_layer_objects.Add(z, new List<tile>()); z_layer_objects[z].Add(new tile(extract_png(png, f), x, y, v.x, v.y, flipped)); } } } toolStripStatusLabel1.Text = "Getting Tiles..."; t_node = FindNode(layer_node, "info"); if (t_node.Nodes.Count > 0) { tS_tile = (string)(FindNode(t_node, "tS").Tag); } t_node = FindNode(layer_node, "tile"); if ((t_node.Nodes.Count > 0)) { for (i = 0; i < t_node.Nodes.Count; i++) { t_node2 = FindNode(t_node, i.ToString()); if (t_node2 != null) { found_node = FindNode(t_node2, "x"); if (found_node != null) { x = (int)found_node.Tag; } found_node = FindNode(t_node2, "y"); if (found_node != null) { y = (int)found_node.Tag; } found_node = FindNode(t_node2, "zM"); if (found_node != null) { z = (int)found_node.Tag; } string u_tile = "", no_tile = ""; found_node = FindNode(t_node2, "u"); if (found_node != null) { u_tile = (string)(found_node.Tag); } found_node = FindNode(t_node2, "no"); if (found_node != null) { no_tile = found_node.Tag.ToString();} tile_img = FindImage("Map\\Tile\\" + tS_tile + ".img", treeView1.Nodes[0]); PNG png = (PNG)get_value(u_tile + "\\" + no_tile, tile_img); found_node = FindByFullPath(u_tile + "\\" + no_tile , tile_img.node); found_node = FindNode(found_node, "origin"); if (found_node != null) { v = (vector)found_node.Tag; } found_node = FindByFullPath(u_tile + "\\" + no_tile, tile_img.node); found_node = FindNode(found_node, "z"); if (found_node != null) { z += (int)found_node.Tag; } if (z_layer_tiles.ContainsKey(z)) { z_layer_tiles[z].Add(new tile(extract_png(png, f), x, y, v.x, v.y, flipped)); } else { z_layer_tiles.Add(z, new List<tile>()); z_layer_tiles[z].Add(new tile(extract_png(png, f), x, y, v.x, v.y, flipped)); } } } } toolStripStatusLabel1.Text = "Adding Objects"; foreach (KeyValuePair<int, List<tile>> z_layer in z_layer_objects) { foreach (tile t in z_layer.Value) { if (!t.flip) { gMap.DrawImage(t.pic, t.x + centerX - t.ox, t.y + centerY - t.oy); } else { Bitmap flippedBmp = t.pic; flippedBmp.RotateFlip(RotateFlipType.RotateNoneFlipX); gMap.DrawImage(flippedBmp, t.x + centerX + t.ox - flippedBmp.Width, t.y + centerY - t.oy); } } } toolStripStatusLabel1.Text = "Adding Tiles..."; foreach (KeyValuePair<int, List<tile>> z_layer in z_layer_tiles) { foreach (tile t in z_layer.Value) { if (!t.flip) { gMap.DrawImage(t.pic, t.x + centerX - t.ox, t.y + centerY - t.oy); Console.WriteLine(String.Format("set position X {0} {1}",t.x,t.ox)); Console.WriteLine(String.Format("set position Y {0} {1}", t.y, t.oy)); Console.WriteLine(String.Format("set map {0} {1}", centerX, centerY)); } else { Bitmap flippedBmp = t.pic; flippedBmp.RotateFlip(RotateFlipType.RotateNoneFlipX); gMap.DrawImage(flippedBmp, t.x + centerX + t.ox - flippedBmp.Width, t.y + centerY - t.oy); } } } return bMap; }