I am in ap Computer Science and as a project I decided to create a program that can find the derivative of an equation using the power rule so like 4x^3 becomes 3x^2. I have figured to make this work perfectly with single digit numbers as the coefficiant but I am trying to figure a way out with multiple digits. So like 56x^5 becomes 280x^4.
I know my code is a bit messy and could be more organized by using methods but i am just getting started and will work on it in the near future. The code is below and thank you for your help!
import java.util.ArrayList;
import java.util.Scanner;
//finds the derivative of an equation (Example: input: 2x^3+5x^4 Output: 6x^2+20x^3)
public class derivative {
public static void main(String[] args) {
//input of polynomial
System.out.println("Enter polynomial:");
Scanner sc = new Scanner(System.in);
String polynomialEquation = sc.nextLine();
//A string array list is created with the polynomial
ArrayList<String> equationArr = new ArrayList<String>();
for (int i = 0; i<polynomialEquation.length(); i++) {
equationArr.add(polynomialEquation.substring(i, i+1));
}
ArrayList<String> intStrings = new ArrayList<String>();
//separate the numbers from the list
for(int i =0; i<equationArr.size(); i++)
{
if (equationArr.get(i).equals("1") || equationArr.get(i).equals("2") || equationArr.get(i).equals("3") ||equationArr.get(i).equals("4") ||equationArr.get(i).equals("5") ||
equationArr.get(i).equals("6") || equationArr.get(i).equals("7") || equationArr.get(i).equals("8") || equationArr.get(i).equals("9") || equationArr.get(i).equals("0"))
{
String addVal = equationArr.get(i);
intStrings.add(addVal);
equationArr.remove(i);
}
}
//convert string integers to integers
ArrayList<Integer> deriveInt = new ArrayList<Integer>(intStrings.size());
for (String myInt : intStrings)
{
deriveInt.add(Integer.valueOf(myInt));
}
//derive coefficiants
for (int i = 0; i<deriveInt.size()-1;i +=2) {
deriveInt.set(i, deriveInt.get(i)*deriveInt.get(i+1));
}
//derive exponent
for(int i = 1; i< deriveInt.size(); i +=2) {
deriveInt.set(i,deriveInt.get(i)-1);
}
//convert integer back to string
ArrayList<String> stringDerive = new ArrayList<String>();
for (Integer myInt2 : deriveInt)
{
stringDerive.add(String.valueOf(myInt2));
}
//get the signs from the original equation
ArrayList<String> sign = new ArrayList<String>();
sign.add("0");
for(int i =0; i<equationArr.size(); i++) {
if(equationArr.get(i).equals("+") || equationArr.get(i).equals("-"))
{
sign.add(equationArr.get(i));
equationArr.remove(i);
}
}
System.out.println(stringDerive);
System.out.println(sign);
int coefficiant = 0;
for (int i = 0; i < stringDerive.size()/2; i++) {
System.out.print(stringDerive.get(coefficiant));
System.out.print("x^");
System.out.print(stringDerive.get(coefficiant+1));
coefficiant = coefficiant + 2;
if (sign.indexOf("-") != -1 || sign.indexOf("+") != -1) {
int signCount = 1;
System.out.print(sign.get(signCount));
sign.remove(1);
}
}
}
}
Comments
Post a Comment