static void Main(string[] args) { // Дано квадратное уравнение вида // x^2+2x-3=0 var quadratic = new Quadratic() { A = 1, B = 2, C = -3 }; // Инструмент для решения квадратного уравнения var resolver = new QuadraticSolver(); // Результат решения квадратного уравнения var roots = resolver.Solve(quadratic); // Вывод результата решения задачи if (roots.HasRoots) { Console.WriteLine($"x1 = {roots.Root1}, x2 = {roots.Root2}"); } else { Console.WriteLine("Корней нет"); } Console.ReadKey(); }
public void Quadratic_0_0_0_has_solution_0() { QuadraticSolver solver = new QuadraticSolver(0, 0, 0); List <double> answer = solver.SolveQuadratic(); Assert.AreEqual(2, answer.Count, "Number of solutions for the quadratic 0, 0, 0 is not equal to 2"); Assert.AreEqual(0, answer[0], "The solution to the quadratic 0, 0, 0 is not equal to 0"); }
public void Lock(ZACommons commons, EventDriver eventDriver) { if (Mode != Modes.Locked) { return; } var shipControl = (ShipControlCommons)commons; // Guesstimate current target position var delta = eventDriver.TimeSinceStart - LastTargetUpdate; var targetGuess = TargetAimPoint + TargetVelocity * delta.TotalSeconds; // Solve for intersection of expanding sphere + moving object // Note sphere may have an initial radius (to account for offset from // CoM) and may only start expanding after some delay (to account for // firing sequence + acceleration). var offset = targetGuess - shipControl.ReferencePoint; var tVelSquared = Vector3D.Dot(TargetVelocity, TargetVelocity); var a = tVelSquared - ShellSpeed * ShellSpeed; var offsetDotVel = Vector3D.Dot(offset, TargetVelocity); var b = 2.0 * (tVelSquared * ShellFireDelay + offsetDotVel - ShellOffset * ShellSpeed); var c = Vector3D.Dot(offset, offset) + ShellFireDelay * ShellFireDelay * tVelSquared + 2.0 * ShellFireDelay * offsetDotVel - ShellOffset * ShellOffset; double interceptTime = 0.0; double s1, s2; int solutions = QuadraticSolver.Solve(a, b, c, out s1, out s2); // Pick smallest positive intercept time if (solutions == 1) { if (s1 > 0.0) { interceptTime = s1; } } else if (solutions == 2) { if (s1 > 0.0) { interceptTime = s1; } else if (s2 > 0.0) { interceptTime = s2; } } var prediction = targetGuess + TargetVelocity * interceptTime; double yawPitchError; seeker.Seek(shipControl, prediction - shipControl.ReferencePoint, out yawPitchError); eventDriver.Schedule(1, Lock); }
public void FindRoots_FirstTermIsZero_ReturnsCorrectAnswer() { double a = 0; double b = 1; double c = 3; List <Complex> roots = QuadraticSolver.FindRoots(a, b, c); Complex root = new Complex(-3, 0); Assert.AreEqual(1, roots.Count); Assert.IsTrue(roots.Exists(x => x == root)); }
public void FindRoots_ComplexRoots_ReturnsCorrectAnswer() { double a = 1; double b = -2; double c = 4; List <Complex> roots = QuadraticSolver.FindRoots(a, b, c); Complex root1 = new Complex(1, Math.Sqrt(3)); Complex root2 = new Complex(1, -Math.Sqrt(3)); Assert.AreEqual(2, roots.Count); Assert.IsTrue(roots.Exists(x => x == root1)); Assert.IsTrue(roots.Exists(x => x == root2)); }
public void FindRoots_IdenticalRealRoots_ReturnsCorrectAnswer() { double a = 1; double b = -4; double c = 4; List <Complex> roots = QuadraticSolver.FindRoots(a, b, c); Complex root1 = new Complex(2, 0); Complex root2 = new Complex(2, 0); Assert.AreEqual(2, roots.Count); Assert.IsTrue(roots.Exists(x => x == root1)); Assert.IsTrue(roots.Exists(x => x == root2)); }
private static IEquationSolutions Solve(string variable, IExpression expression, ClassificationResult classification) { if (classification.EquationType == EquationTypes.Undefined) { return(new EquationSolutions()); } if (classification.SearchResult.ElementAt(0).Key != variable) { //var expression = equation.Left; //var classification = equation.Classification; //var clone = expression.Clone(); //substitute = new Tuple<string, string>(variable, GetNewVariableForSub(equation)); //var sub = new VariableExpression(substitute.Item2, 1); //clone.Substitute(ref clone, sub, classification.SearchResult.ElementAt(0).Key); var sols = Solve(classification.SearchResult.ElementAt(0).Key, expression, classification); return(sols); } else { if (classification.EquationType == EquationTypes.Linear) { var solver = new LinearSolver(); return(solver.Solve(expression, variable, classification)); } else if (classification.EquationType == EquationTypes.Quadratic) { var solver = new QuadraticSolver(); return(solver.Solve(expression, variable, classification)); } else if (classification.EquationType == EquationTypes.Trigonometric) { var solver = new TrigonometricSolver(); return(solver.Solve(expression, variable, classification)); } else { return(null); } } }
public ComplexNumber solve(function mode) { if (mode.Equals(function.Quadratic)) { IComplexNumberSolver solver = new QuadraticSolver { ComplexNumber = this }; return(solver.solveComplexNumber()); } else if (mode.Equals(function.Qubic)) { IComplexNumberSolver solver = new QubicSolver { ComplexNumber = this }; return(solver.solveComplexNumber()); } else { return(null); } }
public static void Run() { QuadraticSolver quadraticSolver = new QuadraticSolver(); Console.Write("a:"); quadraticSolver.a = double.Parse(Console.ReadLine()); Console.Write("b:"); quadraticSolver.b = double.Parse(Console.ReadLine()); Console.Write("c:"); quadraticSolver.c = double.Parse(Console.ReadLine()); double?rootA, rootB; //Equivalent to "Nullable<double> rootA, rootB;" bool areRootsFound = quadraticSolver.Solve(out rootA, out rootB); //Usage of "var.Value" instead of "var" is recommended //for nullable types (does not give access to same methods) string message = (areRootsFound ? $"roots = {rootA.Value:0.000}, {rootB.Value:0.000}" : "No real root found"); Console.WriteLine(message); Console.ReadLine(); }
private void btnGo_Click(object sender, EventArgs e) { if (cbOperation.Text.Equals("Quadratic Solver")) { this.Hide(); QuadraticSolver qs = new QuadraticSolver(); qs.ShowDialog(); this.Close(); } else if (!cbOperation.Text.Equals("") && !cbShape.Text.Equals("")) { if (cbOperation.Text.Equals("Calculate Area")) { if (cbShape.Text.Equals("Circle")) { this.Hide(); CircleArea circleArea = new CircleArea(); circleArea.ShowDialog(); this.Close(); } else if (cbShape.Text.Equals("Square")) { this.Hide(); SquareArea squareArea = new SquareArea(); squareArea.ShowDialog(); this.Close(); } else if (cbShape.Text.Equals("Triangle")) { this.Hide(); TriangleArea triangleArea = new TriangleArea(); triangleArea.ShowDialog(); this.Close(); } } else if (cbOperation.Text.Equals("Calculate Perimeter")) { if (cbShape.Text.Equals("Circle")) { this.Hide(); CirclePerimeter circlePerimeter = new CirclePerimeter(); circlePerimeter.ShowDialog(); this.Close(); } else if (cbShape.Text.Equals("Square")) { this.Hide(); SquarePerimeter squarePerimeter = new SquarePerimeter(); squarePerimeter.ShowDialog(); this.Close(); } else if (cbShape.Text.Equals("Triangle")) { this.Hide(); TrianglePerimeter trianglePerimeter = new TrianglePerimeter(); trianglePerimeter.ShowDialog(); this.Close(); } } } }
static void Main(string[] args) { int choose; double a = 0; double b = 0; double c = 0; string pathFile = ConfigurationManager.AppSettings["log"]; StreamWriter writer = new StreamWriter(pathFile, true); while (true) { Console.WriteLine(" Выберите действие"); Console.WriteLine("0. Линейное уравнение"); Console.WriteLine("1. Квадратное уравнение"); Console.WriteLine("2. Перемножить матрицу (данные из файла)"); Console.WriteLine("3. Выход"); while (true) { if (Int32.TryParse(Console.ReadLine(), out choose)) { break; } else { Console.WriteLine("Введите пожалуйста цифру из предложенных"); } } switch (choose) { case 0: Console.WriteLine("Ax + B = 0"); Console.WriteLine("Введите коэффиценты А и В"); while (true) { Console.WriteLine("Введите A"); if (Double.TryParse(Console.ReadLine(), out a)) { break; } else { Console.WriteLine("Введите пожалуйста цифру"); writer.WriteLine($"Линейное уравнение (ВВОД НЕКОРРЕКТНЫХ ДАННЫХ : А={a} "); } } while (true) { Console.WriteLine("Введите B"); if (Double.TryParse(Console.ReadLine(), out b)) { break; } else { Console.WriteLine("Введите пожалуйста цифру"); writer.WriteLine($"Линейное уравнение (ВВОД НЕКОРРЕКТНЫХ ДАННЫХ : B={b} "); } } LinearSolver linearEquation = new LinearSolver(a, b); Console.WriteLine("Корень уравнения: " + linearEquation.solve()); writer.WriteLine($"Линейное уравнение : {a}x+{b} = 0" + "\tКорень уравнения : " + linearEquation.solve()); Console.ReadLine(); break; case 1: Console.WriteLine("Ax^2 + Bx + C = 0"); Console.WriteLine("Введите коэффиценты А,B и С"); while (true) { Console.WriteLine("Введите A"); if (Double.TryParse(Console.ReadLine(), out a)) { break; } else { Console.WriteLine("Введите пожалуйста цифру"); writer.WriteLine($"Квадратное уравнение (ВВОД НЕКОРРЕКТНЫХ ДАННЫХ : А={a} "); } } while (true) { Console.WriteLine("Введите B"); if (Double.TryParse(Console.ReadLine(), out b)) { break; } else { Console.WriteLine("Введите пожалуйста цифру"); writer.WriteLine($"Квадратное уравнение (ВВОД НЕКОРРЕКТНЫХ ДАННЫХ : B={b} "); } } while (true) { Console.WriteLine("Введите C"); if (Double.TryParse(Console.ReadLine(), out c)) { break; } else { Console.WriteLine("Введите пожалуйста цифру"); writer.WriteLine($"Квадратное уравнение (ВВОД НЕКОРРЕКТНЫХ ДАННЫХ : C={c} "); } } QuadraticSolver quadriticEquation = new QuadraticSolver(a, b, c); double[] result = quadriticEquation.solve(); Console.WriteLine($" Корни уравнения : x1= {result[1]} x2= {result[2]}"); writer.WriteLine($"Квадратное уравнение : {a}x^2 + {b}x + c = 0 " + $" Корни уравнения : x1= {result[1]} x2= {result[2]}"); Console.ReadLine(); break; case 2: string matrix1 = ConfigurationManager.AppSettings["matrix1"]; string matrix2 = ConfigurationManager.AppSettings["matrix2"]; double[,] A = MatrixSolver.readMatrix(matrix1); double[,] B = MatrixSolver.readMatrix(matrix1); Console.WriteLine(); Console.WriteLine("Матрицв А"); MatrixSolver.printMatrix(A); Console.WriteLine(); Console.WriteLine("Матрицв B"); MatrixSolver.printMatrix(B); Console.WriteLine(); double[,] answer = MatrixSolver.Multuply(A, B); if (answer == null) { Console.WriteLine("Перемножение невозможно"); } else { Console.WriteLine("Результат"); MatrixSolver.printMatrix(answer); } Console.ReadKey(); break; case 3: writer.Close(); Environment.Exit(0); break; } } }
public void ProcessOptiTrackData(OptiTrack.InputFrame data) { // Pozycja przekonwertowana z układu optitracka do układu odpowiedniej KUKI var position = robot.OptiTrackTransformation.Convert(data.Position); double ballX = position[0]; double ballY = position[1]; double ballZ = position[2]; if (ballZ < 0) { ballFell = true; } // Zamiast zabawy w te ify trzeba ogarnac LabeledMarkers w optitracku zeby wykryc kiedy dokladnie widzimy pileczke a kiedy nie if (!ballFell && ballX < 1200 && ballX != 791.016 && ballY != 743.144 && ballZ != 148.319) { Console.WriteLine("cc"); if (polyfitZ.Values.Count == maxPolyfitPoints) { for (int i = 0; i < maxPolyfitPoints / 2; i++) { polyfitX.Values[i] = polyfitX.Values[2 * i]; polyfitY.Values[i] = polyfitY.Values[2 * i]; polyfitZ.Values[i] = polyfitZ.Values[2 * i]; } polyfitX.Values.RemoveRange(maxPolyfitPoints / 2, maxPolyfitPoints / 2); polyfitY.Values.RemoveRange(maxPolyfitPoints / 2, maxPolyfitPoints / 2); polyfitZ.Values.RemoveRange(maxPolyfitPoints / 2, maxPolyfitPoints / 2); } polyfitX.AddPoint(elapsedTime, ballX); polyfitY.AddPoint(elapsedTime, ballY); polyfitZ.AddPoint(elapsedTime, ballZ); var xCoeffs = polyfitX.CalculateCoefficients(); var yCoeffs = polyfitY.CalculateCoefficients(); var zCoeffs = polyfitZ.CalculateCoefficients(); var roots = QuadraticSolver.SolveReal(zCoeffs[2], zCoeffs[1], zCoeffs[0] - zPositionAtHit); elapsedTime += data.FrameDeltaTime; if (roots.Length != 2) { // No real roots return; } double T = roots[1]; chart.AddPoint(T, T); var ballTargetVelocity = Vector <double> .Build.DenseOfArray(new double[] { xCoeffs[1], yCoeffs[1], 2 * zCoeffs[2] * T + zCoeffs[1] }); Vector <double> paddleNormal = Normalize(reflectionVector) - Normalize(ballTargetVelocity); if (IsTimeStable(T) && polyfitX.Values.Count >= 10) { double timeToHit = T - elapsedTime; double predX = xCoeffs[1] * T + xCoeffs[0]; double predY = yCoeffs[1] * T + yCoeffs[0]; Console.WriteLine("T: " + T + " X: " + predX + " Y: " + predY); if (!ballHit && timeToHit >= 0.05) // 0.1 DO SPRAWDZENIA! { double angleB = Math.Atan2(paddleNormal[0], paddleNormal[2]) * 180.0 / Math.PI; double angleC = -90.0 - Math.Atan2(paddleNormal[1], paddleNormal[2]) * 180.0 / Math.PI; RobotVector predictedHitPosition = new RobotVector( predX, predY, zPositionAtHit, 0, angleB, angleC ); //if (robot.Limits.WorkspaceLimits.CheckPosition(predictedHitPosition)) { // //predkosc na osiach w [mm/s] // // RobotVector velocity = new RobotVector(0, 0, 0); // // Dla odwaznych: // RobotVector velocity = new RobotVector(0, 0, 150); // robot.MoveTo(predictedHitPosition, velocity, timeToHit); // robotMoved = true; //} } } } }
public void Run(ZACommons commons, EventDriver eventDriver) { var shipControl = (ShipControlCommons)commons; Vector3D?velocity = shipControl.LinearVelocity; if (velocity != null) { // Interpolate position since last update var delta = eventDriver.TimeSinceStart - LastTargetUpdate; var targetGuess = TargetAimPoint + TargetVelocity * delta.TotalSeconds; // Solve for intersection of expanding sphere + moving object var offset = targetGuess - shipControl.ReferencePoint; var a = Vector3D.Dot(TargetVelocity, TargetVelocity) - Vector3D.Dot((Vector3D)velocity, (Vector3D)velocity); var b = 2.0 * Vector3D.Dot(offset, TargetVelocity); var c = Vector3D.Dot(offset, offset); double interceptTime = 20.0; double s1, s2; int solutions = QuadraticSolver.Solve(a, b, c, out s1, out s2); // Pick smallest positive intercept time if (solutions == 1) { if (s1 > 0.0) { interceptTime = s1; } } else if (solutions == 2) { if (s1 > 0.0) { interceptTime = s1; } else if (s2 > 0.0) { interceptTime = s2; } } var prediction = targetGuess + TargetVelocity * interceptTime; // Determine relative vector to aim point var targetVector = prediction - shipControl.ReferencePoint; // Project onto our velocity var velocityNorm = Vector3D.Normalize((Vector3D)velocity); var forwardProj = velocityNorm * Vector3D.Dot(targetVector, velocityNorm); // Use scaled rejection for oversteer var forwardRej = (targetVector - forwardProj) * OVERSTEER_FACTOR; // Add to projection to get adjusted aimpoint var aimPoint = forwardProj + forwardRej; double yawPitchError; seeker.Seek(shipControl, aimPoint, out yawPitchError); } else { // Can't really do crap w/o our own velocity shipControl.GyroControl.Reset(); } eventDriver.Schedule(FramesPerRun, Run); }