***Write a method in Java to Evaluate:
***For exp: object t2 has coefficient = 2.4 and exponent = 3. it represents 2.4 * x^3. Then t2.evaluate(-1.5) is 2.4 * -1.5^3 which is -8.1.
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class PolyTermTest{
public static int score = 0;
public static String result = "";
public static String currentMethodName = null;
ArrayList methodsPassed = new ArrayList();
PolyTerm t1, t2, t3, t4;
@BeforeEach
public void setUp() throws Exception {
currentMethodName = null;
t1 = new PolyTerm(1, 1); //x
t2 = new PolyTerm(2.4, 3); //2.4x^3
t3 = new PolyTerm(-1.5, 0); //-1.5
t4 = new PolyTerm(3.6, -2); //3.6x^-2
}
@Test @Order(2) @Graded(marks=8, description="evaluate(double)")
public void testEvaluate() {
assertEquals(1, t1.evaluate(1), 0.001); ///x=1
assertEquals(0, t1.evaluate(0), 0.001);
assertEquals(-1.5, t1.evaluate(-1.5), 0.001);
assertEquals(2.4, t2.evaluate(1), 0.001);///2.4x^3= 2.4*(1)^3
assertEquals(0, t2.evaluate(0), 0.001);
assertEquals(-8.1, t2.evaluate(-1.5), 0.001);
assertEquals(-1.5, t3.evaluate(1), 0.001);///-1.5x=-1.5*1=-1.5
assertEquals(-1.5, t3.evaluate(0), 0.001);
assertEquals(-1.5, t3.evaluate(-1.5), 0.001);
assertEquals(3.6, t4.evaluate(1), 0.001);
assertNull(t4.evaluate(0));
assertEquals(1.6, t4.evaluate(-1.5), 0.001);
currentMethodName = new Throwable().getStackTrace()[0].getMethodName();
}
2/ write a method in Java
@Test @Order(1) @Graded(marks=8, description="PolyTerm(double, int)")
public void testPolyTerm() {
assertEquals(1, t1.coefficient, 0.001);
assertEquals(1, t1.exponent);
assertEquals(2.4, t2.coefficient, 0.001);
assertEquals(3, t2.exponent);
assertEquals(-1.5, t3.coefficient, 0.001);
assertEquals(0, t3.exponent);
assertEquals(3.6, t4.coefficient, 0.001);
assertEquals(-2, t4.exponent);
currentMethodName = new Throwable().getStackTrace()[0].getMethodName();
}
Here is the method evaluate :
float evaluate(float value)
{
float a = Math.pow(value,exponent);
float res = a*coefficient;
return res;
}
as per the given example it is clear that t2 is an object of a class where coefficient and exponent are two predefined variables and this method evaluate should be inside the same class so it can easily access the variables exponent and coefficient.
The java.lang.Math.pow() is used to calculate a number raise to the power of some other number. This function accepts two parameters and returns the value of first parameter raised to the second parameter.
*****WITHOUT MATH.POW( )*****
float evaluate(float value)
{
float a=1.0;
while(exponent>0)
{
a=a*value;
exponent--;
}
float res = a*coefficient;
return res;
}
Get Answers For Free
Most questions answered within 1 hours.