Correcting a formula in java

66 Views Asked by At

My first assignment requires me to write a program that expresses a formula. The formula as written in the assignment :

y   =   4x^3 + 8x^2 - 31x - 35 / (3x2 + 1)^1/2  + 2 * | x - 1.5 |  

          

| means absolute value; (...)1/2 means square root

Also how should I create a code that prints how many times the formula prints out a positive or negative number or zero?

Here is how I created my assignment's program:

import java.io.*;

public class hw1 {

    public static void main(String[] args) throws IOException
    {
        System.out.println("My name is Jibran Khan and this is the output of my first program.");
        
        double x; double y;
        
        PrintWriter outFile = new PrintWriter("testfile.txt");
    
        for(x=-3.00; x <= 3.0; x = x + 0.50)
        { 
        
        y=((4*(x*x*x))) + (8*(x*x))-(31*x)-35/Math.sqrt(3*x*x+1)+2* Math.abs(x-1.5);
        System.out.println("X = " + x + "Y = " + y );
        
        if (y<=0.0) System.out.println("Y is negative");
        if (y>=0.0) System.out.println("Y is positive");
        if (y == 0.0) System.out.println("Y is zero");
        
        }
        
        
        System.out.println();
        System.out.println("My first program is complete");
        
        outFile.close();
        

    }
    
}
2

There are 2 best solutions below

0
On

Calculate the Denominator and Numerator in different variables, that will give more readability and you will be able to spot the mistakes easily.

Also, the conditions you gave for y: (y <= 0.0) and (y >= 0.0) will be true for zero so the last condition y == 0.0 is not reachable.

0
On

OK, you want to make a test on a simple math formula. You have to test the results and define how many results are positive, negative or equal to 0 ... You have to update your tests... It result is equal to 0, your test returns positive, negative and null results.

You also have to count results. So implement counters for each type of results and increment them in the if statement.

public static void main(String[] args) throws IOException {
    double x; double y;
    int positive = 0;
    int negative = 0;    
    int equalZero = 0;
    PrintWriter outFile = new PrintWriter("testfile.txt");

    for(x=-3.00; x <= 3.0; x = x + 0.50) { 
        y = Math.pow(4,3) + ... ( your formula) 
        System.out.println("X = " + x + "Y = " + y );
        if (y < 0.0) {
            System.out.println("Y is negative");
            negative++;
        } else if (y > 0.0) {
            System.out.println("Y is positive");
            positive++;
        } else { 
            System.out.println("Y is zero");
            equalZero++;
        }
    }

    System.out.println();
    System.out.println("Positive results : " + positive);
    System.out.println("Negative results : " + negative);
    System.out.println("Equal to zero   : " + equalZero);
   
    outFile.close();
}