private static bool Solve(float x1, float y1, float x2, float y2, float L, out double a, out double v, out double b) { a = 0; v = 0; b = 0; double d = x2 - x1; double h = y2 - y1; NewtonRaphson.Function f = delegate(double a0) { return(2.0 * a0 * Math.Sinh(d / (2.0 * a0)) - Math.Sqrt((L * L) - (h * h))); }; NewtonRaphson.Function df = delegate(double a0) { return(2.0 * Math.Sinh(d / (2.0 * a0)) - d * Math.Cosh(d / (2.0 * a0)) / a0); }; double newA = NewtonRaphson.FindRoot(0.01 * d, 0.00001, 100, f, df); if (double.IsNaN(newA) || double.IsInfinity(newA)) { return(false); } else { a = newA; double k = 0.5 * (a * Math.Log((L + h) / (L - h)) - d); v = k - x1; b = y1 - a * Math.Cosh(k / a); return(true); } }
public void NoRoot() { Func <double, double> f1 = x => x * x + 4; Func <double, double> df1 = x => 2 * x; Assert.That(() => NewtonRaphson.FindRoot(f1, df1, -5, 5, 1e-14, 50), Throws.TypeOf <NonConvergenceException>()); }
public void IterateIterationsExceededException() { Func <double, double> fx = x => Math.Pow(x, 8) - 100.0; Func <double, double> dydx = x => 8 * Math.Pow(x, 7); Assert.ThrowsException <IterationsExceededException <double> >(() => NewtonRaphson.Iterate(fx, dydx, iterations: 10)); }
private void Button1_Click(object sender, EventArgs e) { if (textBox1.Text != "") { double x1 = Convert.ToDouble(textBox1.Text); NewtonRaphson newton = new NewtonRaphson(); Salida salida = new Salida(); salida = newton.NRaphson(x1); if (salida.Raiz.ToString() == "NaN" || salida.ErrorRelativo.ToString() == "NaN") { salida.ErrorMsje = "Mal elegidos los extremos"; } else { textBox8.Text = Convert.ToDecimal(salida.Raiz).ToString(); textBox7.Text = salida.NroIteraciones.ToString(); textBox6.Text = Convert.ToDecimal(salida.ErrorRelativo).ToString(); } textBox5.Visible = true; textBox5.Text = salida.ErrorMsje; if (salida.ErrorMsje != null) { textBox8.Text = 0.ToString(); textBox7.Text = 0.ToString(); textBox6.Text = 0.ToString(); } } }
public void NewtonRaphson() { Parameter E1 = new Parameter(0.0); Parameter E2 = new Parameter(0.0); Parameter E3 = new Parameter(0.0); Parameter E4 = new Parameter(0.0); Func <double>[] functions = new Func <double>[] { () => 0.005 * (100.0 - E1 - 2.0 * E2) * (1.0 - E1 - E3) - 100.0 * E1, () => 500.0 * Math.Pow(100.0 - E1 - 2.0 * E2, 2.0) - 100.0 * E2, () => 0.5 * (100.0 - E1 - E3 - 2.0 * E4) - 100.0 * E3, () => 10000.0 * Math.Pow(100.0 * E3 - 2.0 * E4, 2.0) - 100.0 * E4 }; Parameter[] parameters = new Parameter[] { E1, E2, E3, E4 }; NewtonRaphson nr = new NewtonRaphson(parameters, functions); for (int i = 0; i < 15; i++) { nr.Iterate(); } double[] result = nr.GetResult(); for (int i = 0; i <= result.Length - 1; i++) { System.Diagnostics.Debug.WriteLine("E" + i.ToString() + "\t" + result[i].ToString()); } }
public void LocalMinima() { Func <double, double> f1 = x => x * x * x - 2 * x + 2; Func <double, double> df1 = x => 3 * x * x - 2; Assert.AreEqual(0, f1(NewtonRaphson.FindRoot(f1, df1, -5, 6, 1e-14))); //Assert.AreEqual(0, f1(NewtonRaphson.FindRoot(f1, df1, 1, -2, 4, 1e-14, 100))); }
/// <summary> /// Returns the normal water level for a canal section given a flow /// </summary> /// <param name="flow">The flow through the canal section</param> /// <returns></returns> public double GetNormalWaterLevel(double flow) { Func <double, double> equation = (x) => GetManningFlow(x) - flow; NewtonRaphson newtonRaphson = new NewtonRaphson(equation); return(newtonRaphson.Solve(GetCriticalWaterLevel(flow), 0.009)); }
public void BasicEquationNoDerivativeSolve() { double epsilon = 0.0001; NewtonRaphson newtonRaphson = new NewtonRaphson((x => x + 5)); double result = newtonRaphson.Solve(0, epsilon); Assert.IsTrue(Math.Abs(-5 - result) < epsilon); }
public void Iterate() { Func <double, double> fx = x => Math.Pow(x, 8) - 100.0; Func <double, double> dydx = x => 8 * Math.Pow(x, 7); double actual = NewtonRaphson.Iterate(fx, dydx); double expected = 1.77827941003892; Assert.AreEqual(expected, actual); }
private static Complex Iterate(Func <Complex, Complex> fx, Func <Complex, Complex> dydx, Complex?guess = null) { try { return(guess.HasValue ? NewtonRaphson.Iterate(fx, dydx, guess) : NewtonRaphson.Iterate(fx, dydx)); } catch (IterationsExceededException <Complex> exc) { return(exc.LastValue); } }
public void SecondDegreeEquationNoDerivativeSolve2() { double epsilon = 0.0001; NewtonRaphson newtonRaphson = new NewtonRaphson((x => x * x - x - 2)); double result = newtonRaphson.Solve(10, epsilon); double error = Math.Abs(2 - result); Assert.IsTrue(error <= epsilon * 10); }
public static List <NewtonRaphson> newtonRaphson(string expresion, string derivada, double x0, double valorVerdadero, double errorTolerancia, bool hayValorVerdadero) { int iteracion = 0; double x0Ant = 0; double fx0 = 0; double dfx0 = 0; double errorAprox = 0; double errorVerd = 0; //Se realiza iteracion = 0 NewtonRaphson newtonRaphson = null; List <NewtonRaphson> listaNewtonRaphson = new List <NewtonRaphson>(); fx0 = evaluarFuncion(expresion, x0); dfx0 = evaluarFuncion(derivada, x0); newtonRaphson = new NewtonRaphson(iteracion, x0, fx0, dfx0, errorAprox, errorVerd); listaNewtonRaphson.Add(newtonRaphson); do //Se realiza el resto de iteraciones { iteracion++; x0Ant = x0; x0 = x0 - (fx0 / dfx0); fx0 = evaluarFuncion(expresion, x0); dfx0 = evaluarFuncion(derivada, x0); if (hayValorVerdadero) { errorVerd = calcularErrorVerdadero(valorVerdadero, x0); } errorAprox = calcularErrorAproximacion(x0, x0Ant); if (hayValorVerdadero) { newtonRaphson = new NewtonRaphson(iteracion, x0, fx0, dfx0, errorAprox, errorVerd); } else { newtonRaphson = new NewtonRaphson(iteracion, x0, fx0, dfx0, errorAprox, 0); } listaNewtonRaphson.Add(newtonRaphson); } while (errorAprox > errorTolerancia); return(listaNewtonRaphson); }
public ActionResult MetodoNewton() { MetodoNewton_Model model = new MetodoNewton_Model(); model.function1 = "cos(x)-x"; model.function2 = "cos(x)-x"; model.Aproximado = 0.74; model.Tol = 0.0001; model.Iteraciones = 20; NewtonRaphson newton = new NewtonRaphson(); model.ans = new Answer_Model(); model.ans.Res = newton.newtonRaphson(model.function1, model.function2, model.Aproximado, model.Tol, model.Iteraciones); return(View(model)); }
public ActionResult MetodoNewton(MetodoNewton_Model model, string submitbutton) { NewtonRaphson newton = new NewtonRaphson(); model.ans = new Answer_Model(); model.ans.Res = newton.newtonRaphson(model.function1, model.function2, model.Aproximado, model.Tol, model.Iteraciones); if (model.ans.Res[0] == 'L') { model.ans.status = 1; } else { model.ans.status = 2; } return(View(model)); }
public void Cubic() { // with complex roots (looking for the real root only): 3x^3 + 4x^2 + 5x + 6, derivative 9x^2 + 8x + 5 Func <double, double> f1 = x => Polynomial.Evaluate(x, 6, 5, 4, 3); Func <double, double> df1 = x => Polynomial.Evaluate(x, 5, 8, 9); Assert.AreEqual(-1.265328088928, NewtonRaphson.FindRoot(f1, df1, -2, -1, 1e-10), 1e-6); Assert.AreEqual(-1.265328088928, NewtonRaphson.FindRoot(f1, df1, -5, 5, 1e-10), 1e-6); // real roots only: 2x^3 + 4x^2 - 50x + 6, derivative 6x^2 + 8x - 50 Func <double, double> f2 = x => Polynomial.Evaluate(x, 6, -50, 4, 2); Func <double, double> df2 = x => Polynomial.Evaluate(x, -50, 8, 6); Assert.AreEqual(-6.1466562197069, NewtonRaphson.FindRoot(f2, df2, -8, -5, 1e-10), 1e-6); Assert.AreEqual(0.12124737195841, NewtonRaphson.FindRoot(f2, df2, -1, 1, 1e-10), 1e-6); Assert.AreEqual(4.0254088477485, NewtonRaphson.FindRoot(f2, df2, 3, 5, 1e-10), 1e-6); }
public static double Rate(double periods, double presentValue, double futureValue, double monthlyPayment, PaymentType type) { double t = (int)type; double guess = ((monthlyPayment * periods) - presentValue) / presentValue; try { return(NewtonRaphson.Iterate( (double r0) => (((presentValue * Math.Pow(1 + r0, periods)) - futureValue) / ((1 + (r0 * t)) * ((Math.Pow(1 + r0, periods) - 1) / r0))) - monthlyPayment, (double r0) => ((futureValue * ((periods * r0 * r0 * t * Math.Pow(1 + r0, periods)) + (periods * r0 * Math.Pow(1 + r0, periods)) - (r0 * Math.Pow(1 + r0, periods)) - Math.Pow(1 + r0, periods) + r0 + 1)) + (presentValue * Math.Pow(1 + r0, periods) * ((-periods * r0 * r0 * t) + Math.Pow(1 + r0, periods) + (r0 * (Math.Pow(1 + r0, periods) - periods - 1)) - 1))) / ((r0 + 1) * (Math.Pow(1 + r0, periods) - 1) * (Math.Pow(1 + r0, periods) - 1) * ((r0 * t) + 1) * ((r0 * t) + 1)), guess)); } catch (IterationsExceededException <double> exc) { return(exc.LastValue); } }
public static BigInteger Sqrt(BigInteger input) { if (input < 0) { throw new ArgumentOutOfRangeException(nameof(input), ErrorMessages.MustBePositive); } if (input == 0) { return(0); } BigInteger t; try { t = NewtonRaphson.Iterate(x => (x * x) - input, x => 2 * x, 2147483648); } catch (IterationsExceededException <BigInteger> exc) { t = exc.LastValue; } if (t * t == input) { return(t); } --t; BigInteger prev = t * t; while (true) { ++t; BigInteger cur = t * t; if (cur < prev || cur > input) { break; } } return(t - 1); }
public static decimal Rate(int periods, decimal presentValue, decimal futureValue, decimal monthlyPayment, PaymentType type) { decimal t = (int)type; decimal N0 = periods; decimal guess = ((monthlyPayment * periods) - presentValue) / presentValue; try { return(NewtonRaphson.Iterate( (decimal r0) => (((presentValue * DecimalMath.Pow(1M + r0, periods)) - futureValue) / ((1M + (r0 * t)) * ((DecimalMath.Pow(1M + r0, periods) - 1) / r0))) - monthlyPayment, (decimal r0) => ((futureValue * ((N0 * r0 * r0 * t * DecimalMath.Pow(1M + r0, periods)) + (periods * r0 * DecimalMath.Pow(1M + r0, periods)) - (r0 * DecimalMath.Pow(1M + r0, periods)) - DecimalMath.Pow(1M + r0, periods) + r0 + 1)) + (presentValue * DecimalMath.Pow(1M + r0, periods) * ((-N0 * r0 * r0 * t) + DecimalMath.Pow(1M + r0, periods) + (r0 * (DecimalMath.Pow(1 + r0, periods) - periods - 1)) - 1))) / ((r0 + 1) * (DecimalMath.Pow(1 + r0, periods) - 1) * (DecimalMath.Pow(1 + r0, periods) - 1) * ((r0 * t) + 1) * ((r0 * t) + 1)), guess)); } catch (IterationsExceededException <decimal> exc) { return(exc.LastValue); } }
private static ulong SqrtInternal(ulong input) { if (input == 0) { return(0); } double i = input; double value; try { value = NewtonRaphson.Iterate(x => (x * x) - i, x => 2.0 * x, 2147483648); } catch (IterationsExceededException <double> exc) { value = exc.LastValue; } ulong t = (ulong)value; while (t * t < t) { --t; } ulong prev = t * t; while (true) { ++t; ulong cur = t * t; if (cur < prev || cur > input) { break; } } return(t - 1); }
public static double Root(double value, int root) { if (IntegerMath.IsPowerOfTwo(root) && value < 0.0) { throw new ArgumentOutOfRangeException(nameof(value), ErrorMessages.MustBePositive); } else if (value == 0.0) { return(0.0); } try { return(NewtonRaphson.Iterate(x => Math.Pow(x, root) - value, x => root * Math.Pow(x, root - 1), rounding: null)); } catch (IterationsExceededException <double> exc) { return(exc.LastValue); } }
public static decimal Root(decimal value, long root) { if (IntegerMath.IsPowerOfTwo(root) && value < 0.0M) { throw new ArgumentOutOfRangeException(nameof(value), ErrorMessages.MustBePositive); } else if (value == 0.0M) { return(0.0M); } try { return(NewtonRaphson.Iterate(x => PowSquareLaw(x, root) - value, x => root * PowSquareLaw(x, root - 1), rounding: null)); } catch (IterationsExceededException <decimal> exc) { return(exc.LastValue); } }
public void MultipleRootsNearGuess() { // Roots at -2, 2 Func <double, double> f1 = x => x * x - 4; Func <double, double> df1 = x => 2 * x; Assert.AreEqual(0, f1(NewtonRaphson.FindRootNearGuess(f1, df1, 0.5, accuracy: 1e-14))); Assert.AreEqual(-2, NewtonRaphson.FindRootNearGuess(f1, df1, -3.0, accuracy: 1e-14)); Assert.AreEqual(2, NewtonRaphson.FindRootNearGuess(f1, df1, 2.5, accuracy: 1e-14)); Assert.AreEqual(0, f1(NewtonRaphson.FindRootNearGuess(x => - f1(x), x => - df1(x), 0.6, accuracy: 1e-14))); Assert.AreEqual(-2, NewtonRaphson.FindRootNearGuess(x => - f1(x), x => - df1(x), -3, accuracy: 1e-14)); Assert.AreEqual(2, NewtonRaphson.FindRootNearGuess(x => - f1(x), x => - df1(x), 2.5, accuracy: 1e-14)); // Roots at 3, 4 Func <double, double> f2 = x => (x - 3) * (x - 4); Func <double, double> df2 = x => 2 * x - 7; Assert.AreEqual(0, f2(NewtonRaphson.FindRootNearGuess(f2, df2, 0.5, accuracy: 1e-14))); Assert.AreEqual(3, NewtonRaphson.FindRootNearGuess(f2, df2, -0.75, accuracy: 1e-14)); Assert.AreEqual(4, NewtonRaphson.FindRootNearGuess(f2, df2, 4.1, accuracy: 1e-14)); Assert.AreEqual(3, NewtonRaphson.FindRootNearGuess(f2, df2, 3, accuracy: 0.001, maxIterations: 50), 0.001); Assert.AreEqual(3, NewtonRaphson.FindRootNearGuess(f2, df2, 2.75, accuracy: 0.001, maxIterations: 50), 0.001); }
public void MultipleRoots() { // Roots at -2, 2 Func <double, double> f1 = x => x * x - 4; Func <double, double> df1 = x => 2 * x; Assert.AreEqual(0, f1(NewtonRaphson.FindRoot(f1, df1, -5, 6, 1e-14))); Assert.AreEqual(-2, NewtonRaphson.FindRoot(f1, df1, -5, -1, 1e-14)); Assert.AreEqual(2, NewtonRaphson.FindRoot(f1, df1, 1, 4, 1e-14)); Assert.AreEqual(0, f1(NewtonRaphson.FindRoot(x => - f1(x), x => - df1(x), -5, 6, 1e-14))); Assert.AreEqual(-2, NewtonRaphson.FindRoot(x => - f1(x), x => - df1(x), -5, -1, 1e-14)); Assert.AreEqual(2, NewtonRaphson.FindRoot(x => - f1(x), x => - df1(x), 1, 4, 1e-14)); // Roots at 3, 4 Func <double, double> f2 = x => (x - 3) * (x - 4); Func <double, double> df2 = x => 2 * x - 7; Assert.AreEqual(0, f2(NewtonRaphson.FindRoot(f2, df2, -5, 6, 1e-14))); Assert.AreEqual(3, NewtonRaphson.FindRoot(f2, df2, -5, 3.5, 1e-14)); Assert.AreEqual(4, NewtonRaphson.FindRoot(f2, df2, 3.2, 5, 1e-14)); Assert.AreEqual(3, NewtonRaphson.FindRoot(f2, df2, 2.1, 3.9, 0.001, 50), 0.001); Assert.AreEqual(3, NewtonRaphson.FindRoot(f2, df2, 2.1, 3.4, 0.001, 50), 0.001); }
private void button2_Click(object sender, EventArgs e) { string maxIt = Interaction.InputBox("Max iteration : ", "Max iteration", "Exp : 50", 0, 0); int maxIteration = Convert.ToInt32(maxIt); string eps = Interaction.InputBox("Epsilon : ", "Epsilon", "Exp : 0.000001", 0, 0); double Epsilon = Convert.ToDouble(eps); var solver = new NewtonRaphson(); if (radioButton1.Checked) { double root = solver.Solve(x => x * x - 2, x => 2 * x, 1, maxIteration, Epsilon); listBox2.Items.Add(root); } else if (radioButton2.Checked) { double root2 = solver.Solve(x => x - Math.Cos(x), x => 1 + Math.Sin(x), 2, maxIteration, Epsilon); listBox2.Items.Add(root2); } else { MessageBox.Show("Choose a equation"); } }
public PairDouble evaluateResonanceFrequency(ChartTypes type, SignalUnits targetUnits, double approximationResonanceFrequency = 0.0) { int kNumSteps = 4096; // Only acceleration data is used to estimate the resonance frequency SignalUnits baseUnits = SignalUnits.UNKNOWN; if (data[SignalUnits.METERS_PER_SECOND2] != null) { baseUnits = SignalUnits.METERS_PER_SECOND2; } else if (data.ContainsKey(SignalUnits.METERS_PER_SECOND2_PER_FORCE) && data[SignalUnits.METERS_PER_SECOND2_PER_FORCE] != null) { baseUnits = SignalUnits.METERS_PER_SECOND2_PER_FORCE; } if (baseUnits == SignalUnits.UNKNOWN) { return(null); } double[,] complexData = data[baseUnits]; int nData = frequency.Length; double[] realPart = new double[nData]; double[] imagPart = new double[nData]; for (int i = 0; i != nData; ++i) { realPart[i] = complexData[i, 0]; imagPart[i] = complexData[i, 1]; } LinearSpline splineRealPart = LinearSpline.InterpolateSorted(frequency, realPart); LinearSpline splineImagPart = LinearSpline.InterpolateSorted(frequency, imagPart); List <double> resFrequencies = null; Func <double, double> fun = null; Func <double, double> diffFun = null; switch (type) { case ChartTypes.REAL_FREQUENCY: fun = x => splineRealPart.Interpolate(x); diffFun = x => splineRealPart.Differentiate(x); break; case ChartTypes.IMAG_FREQUENCY: fun = x => splineImagPart.Differentiate(x); diffFun = x => splineImagPart.Differentiate2(x); break; } if (fun == null || diffFun == null) { return(null); } double startFrequency = frequency[0]; double endFrequency = frequency[nData - 1]; resFrequencies = findAllRootsBisection(fun, startFrequency, endFrequency, kNumSteps); if (resFrequencies == null || resFrequencies.Count == 0) { return(null); } double distance; double minDistance = Double.MaxValue; int indClosestResonance = 0; int numFrequencies = resFrequencies.Count; for (int i = 0; i != numFrequencies; ++i) { try { resFrequencies[i] = NewtonRaphson.FindRootNearGuess(fun, diffFun, resFrequencies[i], startFrequency, endFrequency); } catch { } distance = Math.Abs(resFrequencies[i] - approximationResonanceFrequency); if (distance < minDistance) { minDistance = distance; indClosestResonance = i; } } double resonanceFrequency = resFrequencies[indClosestResonance]; // Evaluate the amplitude value by using data of the target type if (baseUnits != targetUnits) { complexData = data[targetUnits]; for (int i = 0; i != nData; ++i) { realPart[i] = complexData[i, 0]; imagPart[i] = complexData[i, 1]; } splineRealPart = LinearSpline.InterpolateSorted(frequency, realPart); splineImagPart = LinearSpline.InterpolateSorted(frequency, imagPart); } double realPeak = splineRealPart.Interpolate(resonanceFrequency); double imagPeak = splineImagPart.Interpolate(resonanceFrequency); double ampPeak = Math.Sqrt(Math.Pow(realPeak, 2.0) + Math.Pow(imagPeak, 2.0)); return(new PairDouble(resonanceFrequency, ampPeak)); }
private void Calcular_Click(object sender, RoutedEventArgs e) { ResultadoTextBlock.Text = "Resultado: "; ResultadoTextBlock.Text += NewtonRaphson.NewtonR(double.Parse(ValorInicialTextBox.Text), double.Parse(DecimalesTextBox.Text)); }