Simple Polynomial data structure and Calculator for single variable

Explanation:

The first code takes an integer for the value of the variable and the next one takes a double for the value of variable and produces value of the function.

I have commented the second code to make it easy. Pun intended on lines 144 to 147.

Calculates an equation with given value of the variable. If the equation is,

f(x) = -50x^{-3} +3x -40x^2 +10x^{-5} -7x^{10}

then for,

x = -3, \ f(x) = -413710.189300 \\  x = -2, \ f(x) = -7328.062500 \\  x = -1, \ f(x) = -10.000000 \\  x = 0, \ \ \ f(x) = \ \ \ Undefined \\  x = 1, \ \ \ f(x) = -84.000000 \\  x = 2, \ \ \ f(x) = -7327.937500 \\  x = 3, \ \ \ f(x) = -413695.810700 \\

(Pease Test this code before using, I haven’t done much testing). Check against this site. To use this from console comment freopen lines. Otherwise make two txt files named input and output in the same directory as the cpp file and follow the given equation input format.

Input:
-50x^-3 +3x^+1 -40x^+2 +10x^-5 -7x^+10
0
y
-3
y
-2
y
-1
y
0
y
1
y
2
y
3
n
Output:
-50x^-3 +3x^+1 -40x^+2 +10x^-5 -7x^+10 
Calculate value of Equation for given value (y/n)?
Enter value for the variable.
>>	 -413710.189300
Calculate value of Equation for given value (y/n)?
Enter value for the variable.
>>	 -7328.062500
Calculate value of Equation for given value (y/n)?
Enter value for the variable.
>>	 -10.000000
Calculate value of Equation for given value (y/n)?
Enter value for the variable.
Sorry Try something different
Calculate value of Equation for given value (y/n)?
Enter value for the variable.
>>	 -84.000000
Calculate value of Equation for given value (y/n)?
Enter value for the variable.
>>	 -7327.937500
Calculate value of Equation for given value (y/n)?
Enter value for the variable.
>>	 -413695.810700
Calculate value of Equation for given value (y/n)?
Exiting...

Code:

/**
 * Author:    Asif Ahmed
 * Site:      https://quickgrid.wordpress.com
 * Problem:   Simple Polynomial data structure and
 *            Calculator for single variable.
 */

#include<stdio.h>
#include<string.h>
#include<math.h>


#define N 512


char input[N];


struct PolynomialEquation{

    char sign;
    char signExponent;
    int exponent;
    char variable;
    int constant;

    struct PolynomialEquation *next;
};
typedef struct PolynomialEquation node;



node* insertNode(node* current, char sign, int constant, char variable, char signExponent, int exponent){

    node* temp = new node();

    temp->sign = sign;
    temp->signExponent = signExponent;
    temp->exponent = exponent;
    temp->variable = variable;
    temp->constant = constant;

    temp->next = NULL;
    current->next = temp;
    current = temp;

    return current;
}


void printEquation(node* dummy){
    node* tmp = dummy->next;
    while( tmp != NULL ){
        printf("%c%d%c^%c%d ", tmp->sign, tmp->constant, tmp->variable, tmp->signExponent, tmp->exponent);
        tmp = tmp->next;
    }
    printf("\n");
}


void calculateEquation(node* dummy, int var){

    double sum = 0;
    bool calculable;


    node* tmp = dummy->next;
    while( tmp != NULL ){

        double constantValue = 0, variableValue = 0;
        calculable = true;


        constantValue = tmp->constant;
        if(tmp->sign == '-')
            constantValue *= -1;


        variableValue = pow(var, tmp->exponent);
        if(tmp->signExponent == '-'){
            if(variableValue)
                variableValue = (double) 1 / variableValue;
            else
                calculable = false;
        }


        sum = sum + variableValue * constantValue;
        tmp = tmp->next;


        if(!calculable){
            printf("Sorry Try something different\n");
            break;
        }

    }

    if(calculable)
        printf(">>\t %f\n", sum);

}


int main(){

    // Comment these lines to do I/O operation in console.
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);



    char sign;
    char signExponent;
    int exponent;
    char variable;
    int constant;



    node* dummy = new node();
    dummy->variable = '$';
    node* current = dummy;


    while( scanf("%c%d%c%*c%c%d", &sign, &constant, &variable, &signExponent, &exponent ) == 5){
        getchar();
        current = insertNode(current, sign, constant, variable, signExponent, exponent);
    }

    printEquation(dummy);


    while(1){
        printf("Calculate value of Equation for given value (y/n)?\n");

        char choice = getchar();

        if( choice == 'y' ){
            printf("Enter value for the variable.\n");

            int variableValue;
            scanf("%d", &variableValue);
            getchar();

            calculateEquation(dummy, variableValue);
        }else{
            printf("Exiting...\n");
            break;
        }
    }

    return 0;
}

 

Working with float numbers:

If the equation is,

f(x) = - 4x^{2} - 4x - 9

Input:
+4x^+2 -4x^+1 -9x^+0
0
y
5
y
2.5
y
1.25
y
1.875
n
Output:
+4x^+2 -4x^+1 -9x^+0 
Calculate value of Equation for given value (y/n)?
Enter value for the variable:
>>	 71.000000
Calculate value of Equation for given value (y/n)?
Enter value for the variable:
>>	 6.000000
Calculate value of Equation for given value (y/n)?
Enter value for the variable:
>>	 -7.750000
Calculate value of Equation for given value (y/n)?
Enter value for the variable:
>>	 -2.437500
Calculate value of Equation for given value (y/n)?
Exiting...

Code for float:

/**
 * Author:    Asif Ahmed
 * Site:      https://quickgrid.wordpress.com
 * Problem:   Simple Polynomial data structure and
 *            Calculator with single variable.
 */

#include<stdio.h>
#include<string.h>
#include<math.h>


#define N 512


char input[N];


struct PolynomialEquation{

    char sign;
    char signExponent;
    int exponent;
    char variable;
    int constant;

    struct PolynomialEquation *next;
};
typedef struct PolynomialEquation node;



node* insertNode(node* current, char sign, int constant, char variable, char signExponent, int exponent){

    node* temp = new node();


    temp->sign = sign;
    temp->signExponent = signExponent;
    temp->exponent = exponent;
    temp->variable = variable;
    temp->constant = constant;


    temp->next = NULL;
    current->next = temp;
    current = temp;


    return current;
}


void printEquation(node* dummy){

    // dummy is just an empty node to keep track of front of equation.
    // It is not part of equation. Equation starts after dummy node.
    node* tmp = dummy->next;

    // Print the equation term by term.
    while( tmp != NULL ){
        printf("%c%d%c^%c%d ", tmp->sign, tmp->constant, tmp->variable, tmp->signExponent, tmp->exponent);
        tmp = tmp->next;
    }
    printf("\n");

}


void calculateEquation(node* dummy, double var){

    double sum = 0;
    bool calculable;


    // dummy->next because dummy node is not a part of the equation.
    node* tmp = dummy->next;

    while( tmp != NULL ){

        double constantValue = 0, variableValue = 0;
        calculable = true;

        // make constant negative if the sign is negative.
        constantValue = tmp->constant;
        if(tmp->sign == '-')
            constantValue *= -1;


        // calculate the value of the variable with given exponent.
        variableValue = pow(var, tmp->exponent);
        if(tmp->signExponent == '-'){
            if(variableValue)
                variableValue = (double) 1 / variableValue;
            else
                calculable = false;
        }


        // multiply the calculated value of variable with the constant.
        sum = sum + variableValue * constantValue;

        // calculate the next term of the equation.
        tmp = tmp->next;


        // If not calculable. Ex: divide by zero. then print this.
        if(!calculable){
            printf("Sorry Try something different\n");
            break;
        }

    }

    // print the result.
    if(calculable)
        printf(">>\t %f\n", sum);

}


int main(){

    // Comment these lines to do I/O operation in console.
    //freopen("input.txt", "r", stdin);
    //freopen("output.txt", "w", stdout);



    char sign;
    char signExponent;
    int exponent;
    char variable;
    int constant;


    // Dummy node to make insertion code simpler.
    node* dummy = new node();
    dummy->variable = '$';
    node* current = dummy;


    // Take input of equation term by term.
    // If
    //     taking input from console stop input using null terminator ( ctrl + z ).
    // Else
    //     when taking input from file enter a 0 in a line by itself to stop input.
    while( scanf("%c%d%c%*c%c%d", &sign, &constant, &variable, &signExponent, &exponent ) == 5){
        getchar();
        current = insertNode(current, sign, constant, variable, signExponent, exponent);
    }

    // print the
    printEquation(dummy);


    // Enter different values for the variable to get the value of function.
    while(1){
        printf("Calculate value of Equation for given value (y/n)?\n");

        char choice = getchar();

        if( choice == 'y' ){
            printf("Enter value for the variable:\n");

            double variableValue;
            scanf("%lf", &variableValue);
            getchar();

            calculateEquation(dummy, variableValue);
        }else{
            printf("Exiting...\n");
            break;
        }
    }

    return 0;
}

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s