Untitled

mail@pastecode.io avatar
unknown
java
2 years ago
1.9 kB
41
Indexable
Never
package task2;

/**
 *
 * @author HP
 */
public class Term {
    private double coefficient;
    private int exponent;
    
    Term(double coefficient, int exponent) { // jab hum main ke andar new Term(falan, falan) karenge tou wo yahana ayega
        this.coefficient = coefficient;
        this.exponent = exponent;
    }
    
    // getting functions
    
    public double getCoefficient() {
        return coefficient;
    }
    
    public int getExponent() {
        return exponent;
    }
    
}

//-------------------------------

package task2;

import static java.lang.Math.pow;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 *
 * @author HP
 */
public class Polynomial {
    private List<Term> terms; // this.terms
    
    public Polynomial(Term... terms) { // newTerm()  == terms
       this.terms = new ArrayList<>();
       this.terms.addAll(Arrays.asList(terms));
       
       // jo parameters ke andar terms arahi hain, wo saari this.terms mei
       // save horahi hain..
    }
    
    
    public double evaluate(double x) {
        double result = 0.0;
        // foreach loop, iterating through this.terms
        // formula : coeffcient * pow(x,exponent).
        for(Term t : terms) {
            result  += t.getCoefficient() * pow(x,t.getExponent());
        }
        
        return result;
    }
}

//-------------------------------

package task2;

/**
 *
 * @author HP
 */
public class AppClass {
    public static void main(String[] args) {
        Polynomial p = new Polynomial(new Term(2.0, 2), new Term(3.0, 1), new Term(-1.0, 0));
        
        // 2 * x^2 + 3 * x^1 - 1 * x^0
        // at x = 2.0,
        // 2(2)^2 + 3(2)^1 - 1 * (2)^0
        // 8 + 6 - 1
        // 13
        System.out.println(p.evaluate(2.0));
    }
}