C# - Find 1st (first) derivative of a polynomial equation


C# - Find 1st (first) derivative of a polynomial equation

CODE
using System; class Program { public static void Main(string[] args) { //Polynomial Equation: 3x^3 + 4x^2 +0x + 1 //If one of the x term is 0, provide it as 0 in the array double[] polynomialCoefficients = new double[] { 3, 4, 0, 1 }; Console.Write("Polynomial Equation: "); displayPolynomialEquation(polynomialCoefficients); double[] firstDerivative = new double[polynomialCoefficients.Length-1]; for (int i = 0, power = polynomialCoefficients.Length - 1; i < firstDerivative.Length; i++, power--) { firstDerivative[i] = power * polynomialCoefficients[i]; } Console.Write("First Derivative: "); displayPolynomialEquation(firstDerivative); //OUTPUT //Polynomial Equation: 3x^3 + 4x^2 + 0x + 1 //First Derivative: 9x^2 + 8x + 0 Console.ReadKey(); } private static void displayPolynomialEquation(double[] polynomialCoefficients) { string polynomialEquation = ""; for (int i = 0, power = polynomialCoefficients.Length - 1; i < polynomialCoefficients.Length; i++, power--) { if (power == 0) polynomialEquation += polynomialCoefficients[i]; else if (power == 1) polynomialEquation += polynomialCoefficients[i] + "x"; else polynomialEquation += polynomialCoefficients[i] + "x^" + power; if (i < polynomialCoefficients.Length - 1) polynomialEquation += " + "; } Console.WriteLine(polynomialEquation); } }

Comments