sumitmehta
New Member
- Messages
- 215
- Reaction score
- 1
- Points
- 0
Here is a program in C# for Newton Raphson Method. Hope it is useful for somebody.
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace NRMethod
{
public partial class Form1 : Form
{
public struct Polynomial
{
public int Exponent;
public int Coefficient;
public bool isVariable;
};
Polynomial[] polynomial;
public Form1()
{
//This constructor initializes the polynomial
//It can also be initialized at runtime
InitializeComponent();
int polyCount = 0;
initPoly(out polynomial,2);
addTerm(ref polynomial,polyCount,1, 2, true);
polyCount++;
addTerm(ref polynomial, polyCount, -10, 1, false);
polyCount++;
}
public void initPoly(out Polynomial[] Poly,int termCount) {
Poly = new Polynomial[termCount];
}
public void addTerm(ref Polynomial[] Poly,int index,int Coefficient, int Exponent, bool isVariable) {
Poly[index].Coefficient = Coefficient;
Poly[index].Exponent = Exponent;
Poly[index].isVariable = isVariable;
}
public float CalculateValue(Polynomial[] Poly,float value) {
float val=0;
float e=1;
int polyCount = Poly.Length;
for (int i = 0; i < polyCount; i++) {
if (Poly[i].isVariable==true)
{
for (int j = 0; j < Poly[i].Exponent; j++)
e *= value;
e *= Poly[i].Coefficient;
val += e;
}
else {
val += Poly[i].Coefficient;
}
e = 1;
}
return val;
}
public Polynomial[] Derivative(Polynomial[] Poly) {
Polynomial[] d;
int tCount = 0;
int polyCount = Poly.Length;
for (int i = 0; i < polyCount; i++) {
if (Poly[i].isVariable)
tCount++;
}
d = new Polynomial[tCount];
tCount = 0;
for (int i = 0; i < polyCount; i++)
{
int coeff, exp;
bool isvar = true;
if (Poly[i].isVariable)
{
coeff = Poly[i].Coefficient * Poly[i].Exponent;
exp = Poly[i].Exponent - 1;
if (exp == 0)
isvar = false;
addTerm(ref d, tCount, coeff, exp, isvar);
tCount++;
}
}
return d;
}
public float FindInitialValue(Polynomial[] Poly)
{
float init=0;
int[] roots = new int[2];
roots[0]=0;
float c = CalculateValue(Poly,0);
for (int i = 0; ; i++) {
float v = CalculateValue(Poly,i);
if ((v < 0 && c < 0) | (v > 0 && c > 0))
{
c = v;
roots[0] = i;
continue;
}
else if ((c < 0 && v > 0) | (c > 0 && v < 0))
{
roots[1] = i;
break;
}
}
if(Math.Abs(0-roots[0])>Math.Abs(0-roots[1]))
init=roots[1];
else
init=roots[0];
return init;
}
public float NR(Polynomial[] Poly) {
float nr = 0, n = 0;
float x = FindInitialValue(Poly);
Polynomial[] der = Derivative(Poly);
n = x - (CalculateValue(Poly, x) / CalculateValue(der, x));
do
{
nr = n;
x = n;
n = x - (CalculateValue(Poly, x) / CalculateValue(der, x));
}
while ((Math.Abs(nr - n) >= 0.00001f));
return n;
}
private void button1_Click(object sender, EventArgs e)
{
float n = NR(polynomial);
MessageBox.Show(n.ToString());
}
}
}