Vulpes12y agoPosted Dec 1, 2013, 2:15 PMHere's a simple Polynomial class which also includes a method to solve it using the Newton-Raphson method:using System;using System.Text;public class Polynomial{ int degree; double[] terms; public Polynomial(double[] terms) { this.terms = terms; this.degree = terms.Length - 1; } public Polynomial Differentiate() { if (degree == 0) return new Polynomial(new double[] { 0.0 }); double[] deriv = new double[degree]; int deg = degree; int len = terms.Length; for (int i = 0; i < len - 1; i++) { deriv[i] = (deg--) * terms[i]; } return new Polynomial(deriv); } public double Evaluate(double x) { double val = 0; int len = terms.Length; double pow = 1; for (int i = len - 1; i >= 0; i--) { if (terms[i] != 0) { val += terms[i] * pow; } pow *= x; } return val; } public double Solve (double guess) { Polynomial deriv = this.Differentiate(); double x0 = guess; double x1 = x0; double diff; bool convergent = true; int count = 0; do { double divisor = deriv.Evaluate(x0); if (divisor == 0) { convergent = false; break; } x1 = x0 - this.Evaluate(x0)/divisor; diff = Math.Abs(x1 - x0); x0 = x1; count++; } while (diff > 0.00000001 && count < 100); if (!convergent || count == 100) { Console.WriteLine("May be non-convergent. Stopped after " + count + " iterations"); } return x1; } public override string ToString() { StringBuilder sb = new StringBuilder(); int deg = degree + 1; int len = terms.Length; int first = -1; for (int i = 0; i < len; i++) { deg--; if (terms[i] == 0 && len != 1) continue; if (first == -1) first = i; if (terms[i] >= 0) { if (i > first) sb.Append(" + "); if (terms[i] != 1 || i == len - 1) sb.Append(terms[i].ToString()); } else { sb.Append(" - "); if (terms[i] != -1 || i == len - 1) sb.Append((-terms[i]).ToString()); } if (i < len - 2) { sb.Append("x^" + deg.ToString()); } else if (i == len - 2) { sb.Append("x"); } } return sb.ToString(); } }class Newton{ static void Main() { double[] terms = {1, 0, -1, 1}; // x^3 - x + 1 Polynomial p = new Polynomial(terms); Console.WriteLine("The polynomial is {0}", p); double result = p.Solve(1); Console.WriteLine("The method gives a root of " + result); Console.WriteLine("The residue for this root is " + p.Evaluate(result)); Console.ReadKey(); }}The output is:The polynomial is x^3 - x + 1The method gives a root of -1.32471795724475The residue for this root is 0
VulpesPosted Dec 1, 2013, 2:15 PM
The output is: