Search code examples
javaalgorithmphysicskinematics

Calculating kinematic equations based on user input (a shorter way?)


I'm currently writing a program that will calculate remaining variables for simple kinematic equations in physics. I need to have 4/6 variables and then I can calculate the result for the other two variables. As it stands, I'm using a array of type boolean to detect which variable has been entered or not, and I'm having to compare each case and re-write one of the three formulas to solve for that variable. This is ending up with an absurd amount of bloated code.

Here is an example of just one of the equations in my code:



    if(variableEntered[1] == false && variableEntered[3] == false) {
        // calculate final velocity
       double fvNumber = getInitialVelocity() + (getAcceleration() * (getFinalTime() - getInitialTime())); 
       setFinalVelocity(fvNumber);
       // calculate final position
       double fpNumber = (getInitialPosition() + (getInitialVelocity() * (getFinalTime() - getInitialTime())) + 
           ((0.5 * getAcceleration()) * ((getFinalTime() - getInitialTime()) * (getFinalTime() - getInitialTime()))));
       setFinalPosition(fpNumber);
       System.out.printf("The final velocity is: %.2f m/s.", getFinalVelocity());
       System.out.println();
       System.out.printf("The final position is: %.2f meters.", getFinalPosition());
       System.out.println(); 
       }

 

The three equations I am using are: Vf = Vi + a(tf - ti) Xf = Xi + Vi(tf - ti) + (1/2)a(tf - ti)2 Vf2 - Vi2 = 2a(Xf - Xi)

Is there any way to shorten this or make it easier to implement? Would using an array list somehow work?


Solution

    1. Use BigDecimal to avoid precision loss and incorrect answers due to that.
    2. You can break each formula into its own method, and do each part step by step. The more parentheses the harder it will be to read. for example deltaT = tf-ti; vf = vi + a*deltaT;

    3. If you use BigDecimal or Strings or Wrapper Types such as Double you can check for null instead of keeping a boolean array.