Finding roots of quadratic equation using a specific class - java

i have this assignment that asks me to write a code that determines the roots of a quadratic equation (ax^2 + bx + c = 0). but i have to use the university's library (type.lib.Equation;).
i almost got everything figured out, except the case where there are two roots. i can get the 1st root but i'm still circling around to get the the 2nd root
my code so far
import java.util.Scanner;
import java.io.PrintStream;
import type.lib.Equation;
public class Check05A
{
/**
* #param args
*/
public static void main(String[] args)
{
PrintStream output = System.out;
Scanner input = new Scanner(System.in);
output.println("Enter a,b,c pressing ENTER after each... ");
double a = input.nextDouble();
double b = input.nextDouble();
double c = input.nextDouble();
output.print("The equation: ");
Equation x = new Equation(a, b, c);
output.print(x);
int root = x.getRootCount();
if(root == 0)
{
output.println(" has no real roots.");
}
if(root == 1)
{
double r1 = x.getRoot(root);
output.println(" has the single root: " + r1);
}
if(root == 2)
{
double r1 = x.getRoot(root);
double r2 = -x.getRoot(root);
output.println(" has the two roots: " + r2 + " and " + r1);
}
if(root == -1)
{
output.println("\nis an identity - any value is a root.");
}
}
}
for example 1, 2, -4 should output as :
"has the two roots: -3.23606797749979 and 1.2360679774997898"

You're just putting negative sign to root 1.
This isn't always the case.
Look up the formula for finding the roots for a quadratic equation:
x=\frac{-b \pm \sqrt {b^2-4ac}}{2a}.
and inside your function x.getRoot(), return two values inside an array.

*Please note that this answer is for only TI-84 calculators using If statements to find the roots of any nth degree polynomial. If this does not answer the question for you, please move on.
I made a TI-84 program that is helpful to find the roots of any nth degree polynomial. Here is the code:
(note that Z and S were set to be the derivatives of f and g; you have to find these yourself (I will update this code later with a parameter where it will get f' and g' by itself. Set z and s to 1 to use it to find GCF or roots!) (Also, Y1 is found in vars, if you tab right after clicking vars button, pressing enter, then enter again)
To start, put the function/s that you are working with into Y1, Y2, etc...
enter code here :Prompt F,G`:Prompt Z:Prompt S:If Y1=F:If Y2=G:F*G=FS+GZ->H :If X≥Y:X-Y=I->I:Disp I:If I=0:If I>0:Repeat X-Y=J->J:Disp J
That's it! Super simple, but so helpful! Let me know of any improvements (I am going to make a derivative finder program soon to embed into this code soon!)
Thanks so much, and have fun with the code! -Evan

Related

How can we solve NaN conflict in java?

`java
//5. Write a program to read three sides of triangle and print area for valid data and to print “Invalid data”
// if either one side of the triangle is greater or equals to the sum of other two sides.
package com.company;
import java.util.Scanner;
import java.lang.Math;
public class EX_05 {
public static void main(String[] args) {
Scanner n = new Scanner(System.in);
System.out.println("Enter three sides of a triangle : ");
double a = n.nextDouble();
double b = n.nextDouble();
double c = n.nextDouble();
double s = (a+b+c)/2;
if((a>=(b+c)) || (b>=(a+c)) || (c>=(b+a)) ){
double area = Math.pow((s * (s - a) * (s - b) * (s - c)), 0.5);
System.out.println("The area of triangle is " + area + ".");
}
else {
System.out.println("Invalid data");
}
}
}
`
I wanted to conclude whether the sides of triangle is valid or not to calculate area of triangle.
Here is the output shown by IDE.
Looks like your condition is inverted. You always perform the calculation if the data is invalid and always print "invalid data" if the data is valid.
You should switch what you have in the else with what you have in the if.
Another option would be to add a ! in front of the entire condition.
Yet another would be to invert the logic of the entire condition.
Beyond that, the title of your question is completely unrelated to the actual problem. And please don't paste images of code. They hate that here on stack overflow. Its no fun re-typing all of someone's buggy code on your own machine just to help them find the problem. Post the code itself so it can be easily copied and tested.
Your condition, to check whether the sides form a valid triangle, is wrong. Please correct that and you should get a proper value for area.

Euclid's algorithm shows wrong conclusion

Homework of mine is to create and Euclid's algorithm in java. The task binds me to use both while-loop and if statement. Futhermore - if statement has to be placed inside while-loop.
During this task i faced already infinity-loop problem, somehow manage to get pass it. Now my Euclid's algorithm is giving multiple answers (instead of one) and futhermore they are wrong...
I have searched a couple of topics over here, but none of answers shown in there gave me an answer. I tried to rewrite whole code, and also diffrent conditions for while-loop and if statement.
import java.lang.*;
class EuklidesAlgorithm {
public static void main (String[] args) throws java.lang.Exception{
int a = 25648;
int b = 15468;
while (a % b != 0 ){
int modulo = a % b;
if (modulo == 0){
break;
}else {
modulo = a % b;
System.out.println(" Checking for GCD");
a = b;
b = modulo;
}
System.out.println(" Number " + b + " is GDC of numbers(" + a + "," + b + ").");
}
}
}
I would like it to give a single answer what is GCD for a and b.
First of all the condition :
modulo==0
will alaways be false inside the loop...
and you dont have to change variable prices inside the loop and you also don't have to print answers in every loop so...
the if statement is probably goind to be used to check if any of those two numbers is 0 or if the result is 0 but you can do both

Beginner's Java Code Help: Newton Raphson Square Root Loop

In my Java class for college we are learning about the Looping control structure, and we got an assignment to code a little program that I am guessing is supposed to give the square root of a number and keep on taking the square root until the difference or accuracy is met. Here are the instructions:
"Write a class called NewtonRaphson that can be used to find an approximate solution of sqrt(a) using Newton's method, for any positive real number.
Note: sqrt(a) can be expressed in functional notation as follows: f(x) = x2 – a,
From which f ' (x) = 2 * x,
Print the iteration sequence and the approximation for each iteration. (That is, in a tabular form).
Write a driver class called TestNewton. Use the following data to test the class NewtonRaphson.
• The initial guess is 5.0
• In this exercise, the process terminates when the difference between two consecutive approximations is less than 0.00005"
I have my code linked at the bottom here, the main class and the test class, but I am not getting the looping result I am just getting the same square root of 5 when I type in 5 after running the program. Can someone please tell me where I messed up on?
Thanks, I am really new to coding, and this took forever to make and I had to ask for some friends help.
Main Class: http://pastebin.com/eiUJFJjQ
Test Class: http://pastebin.com/sJ4dB5uZ
Or if you prefer the code here it is:
import java.text.NumberFormat;
import java.text.DecimalFormat;
public class NewtonRaphson {
static final double DIFFERENCE = 0.00005;
double n;
double x;
double derivative;
double function;
double xold;
double xnew;
int i;
public NewtonRaphson(double n2, int x2)
{
n=n2;
x=x2;
function = Math.pow(n, 2)-x;
derivative = 2*n;
xnew=n-function/derivative;
xold=0;
}
boolean positive()
{
return (n >= 0);
}
public double findXNew(double xold2)
{
function = Math.pow(xold2, 2)-x;
derivative = 2*xold2;
return xold2-function/derivative;
}
public void findSqRtA()
{
i=0;
while(Math.abs(xnew-xold)> DIFFERENCE)
{
xold=xnew;
xnew=findXNew(xold);
i++;
System.out.println(this);
}
System.out.println("\nIteration completed, difference is less than 0.00005");
}
public String toString()
{
NumberFormat nf = NumberFormat.getInstance(); DecimalFormat df = (DecimalFormat)nf;
df.applyPattern("0.00000000");
return "The approximate value of the square root of "+x+" is " + xnew + "\n" +
"The number of iterations is " + i;
}
}
and
import java.io.Console;
import java.util.Scanner;
public class TestNewton {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Enter a number you would like to find the square root of");
int a = reader.nextInt();
NewtonRaphson nr = new NewtonRaphson(5.0, a);
nr.findSqRtA();
}
}
My output is this, but I want it to take the square root after each iteration's result.
Enter a number you would like to find the square root of
5
The approximate value of the square root of 5.0 is 2.3333333333333335
The number of iterations is 1
The approximate value of the square root of 5.0 is 2.238095238095238
The number of iterations is 2
The approximate value of the square root of 5.0 is 2.2360688956433634
The number of iterations is 3
The approximate value of the square root of 5.0 is 2.236067977499978
The number of iterations is 4
Iteration completed, difference is less than 0.00005
Newton-Raphson method is very interesting. You can use it to approximate real-valued function roots. x2 is only one of them. Check this fractals produced with Newton-Raphson method. So, do not underestimate Newton-Raphson.
Your code works. But your expectations are mistaken, you think that on every iteration you will update the guess. The code actually does it in the while loop.
You may do something like this, the epsilon may also be a parameter.
First, you give a large epsilon find a square root estimation.
Then input the last approximation with a slightly smaller epsilon, until you are satisfied with the result.
I think this is what you expect.
You can simplify the code. Check this code out.
Your code is actually producing the correct result for me. Therefore I'm not sure what the problem is.
For help with Newton's method you can refer to this article:
http://en.wikipedia.org/wiki/Newton's_method
Can you show us your output?
"I thought the program is supposed to take the square root of each new answer from the previous square root, it constantly takes the square root of 5. But I want it to take the square root of each iteration's result"
Oh, I see, that's because you have this:
NewtonRaphson nr = new NewtonRaphson(5.0, a);
Simply replace the 5.0 above with your previous number.

adding and subtracting for BODMAS system

I have been building a simple formula calculator and have gotten stuck with addition and subtraction. As you should know, when calculating an equation, you follow the arithmetic rules of precedence, i.e. brackets, order: power functions, division, multiplication, addition and subtraction. The problem is that addition and subtraction are given equal priority, so therefore you can read it from left to right. Here is my code so far:
{
ArrayList<String> equation = java.util.Arrays.asList({"2","-","2","+","5"});
while(equation.contains("+")){
addMe(equation);
}
while(equation.contains("-")){
minusMe(equation);
}
}
public static void addMe(ArrayList<String> numberList){
for (int i = 0, n = numberList.size(); i < n; i++) {
String value = (String) numberList.get(i);
if(value.equals("+")){
String wordBefore = (String) numberList.get(i-1);
String wordAfter = (String) numberList.get(i+1);
System.out.println("This is the word before " + wordBefore);
System.out.println("This is the word after " + wordAfter);
double doubleFromBefore = Double.parseDouble(wordBefore);
double doubleFromAfter = Double.parseDouble(wordAfter);
double answer = doubleFromBefore + doubleFromAfter;
System.out.println("This is the answer: " + answer);
String stringAnswer = String.valueOf(answer);
String newNum2 = value.replace(value, stringAnswer);
numberList.set(i,newNum2);
numberList.remove(i-1);
numberList.remove(i);
break;
}
}
}
The minusMe method is exactly the same as the addMe method except with "-" in relevant places. The problem I am having is getting the equation read from left to right one item at a time and either doing the add or subtract method. Ideally I think I need to combine my 2 while loops with an iterator, to solve the problem but my attempts haven't worked. Any idea as to if this will solve my problem? If so please provide amended loop.
Regards
Have a look at this
java.uti.ArrayList<String> equation = java.util.Arrays.asList({"2","-","2","+","5"});
java.util.Iterator<String> equIterator = equation.iterator();
int result = 0;
int multiplier = 1;
while(equIterator.hasNext()){
String operandOrOperator = equIterator.next();
if(operandOrOperator.equals("+")){
multiplier=1;
}else if(operandOrOperator.equals("-")){
multiplier=-1;
}else if(operandOrOperator.equals("*")){
result*=Integer.parseInt(equIterator.next()); // Assuming that next element will be there always after operator.
}else{
result+=(multiplier * Integer.parseInt(operandOrOperator));
}
}
System.out.println("Final result : " + result);
You are doing this all wrong. You need to use at least a recursive-descent expression parser, or Dijkstra's shunting-yard algorithm, maybe even a parser generator if this is going to grow into some kind of a language. You will find all these things via a web search.

How can I shorten an algorithm that employs different scenarios with similar code?

I have developed a program that solves kinematic equations in elementary physics. To solve, one needs 3 out of a possible 5 variables. There are 10 different combinations of what 3 variables are known. I coded 10 scenarios similar to the two blocks of code below
// If we have acceleration, final velocity, and initial velocity
if (varEntered[0] == true && varEntered[1] == true && varEntered[2] == true)
{
double acceleration = knownVariables[0]; //Setting acceleration
double finalVelocity = knownVariables[1]; //Setting finalVelocity
double initVelocity = knownVariables[2]; //Setting initVelocity
double time = ((finalVelocity - initVelocity)/acceleration); //Finding time using an equation
double distance = ((finalVelocity + initVelocity)*((0.5)*time)); //Finding distance using an equation
System.out.println("The time is " + time + " seconds"); //Printing time
System.out.println("The distance is " + distance + " meters"); //Printing distance
}
//If we have distance, final velocity, initial velocity
if (varEntered[3] == true && varEntered[1] == true && varEntered[2] == true)
{
//Known variables
double distance = knownVariables[3]; //Acceleration
double finalVelocity = knownVariables[1]; //Final Velocity
double initVelocity = knownVariables[2]; //Initial Velocity
// Unknown variables
double time = (distance/((0.5)*(finalVelocity + initVelocity))); //Time
double acceleration = ((finalVelocity - initVelocity)/time); //Acceleration
System.out.println("The time is " + time + " meters/second"); //Printing time
System.out.println("The acceleration is " + acceleration + " meters/second^2"); //Printing distance
}
These seem very similar, but are different scenarios. As a programming beginner, I am wondering if the algorithm I use can be modified to shorten the code. If any more info is needed I will be more than happy to provide.
You should define a function that accepts three numbers and performs the general calculation.
For a starter, try this tutorial. Then you can call your function twice, each time with different sets of variables.
I would use a Map and do something like this (warning: pseudocode):
import java.util.HashMap;
import java.util.Map;
Map<String,double> map=new HashMap<String, double>();
Initialize the map with all the values that are known, e.g.:
map.put("initVelocity", 0.35);
Then you can define the following function:
void calculateValues(Map<double,String> map){
if( map.containsKey("initVelocity") && map.containsKey("finalVelocity") && map.containsKey("acceleration")){
map.put("time",((map.get("finalVelocity") - map.get("initVelocity")/map.get("acceleration"));
}
add all the other algorithms here in the same way!!!
}
This function takes the values that are already defined in the HashMap and tries to calculate the missing parameters. It will often be necessary to call it multiple times on a map until all parameters are set. You could do something like:
while( the map has not all values set){
calculateValues(map);
}
Also, you could make sure (by adding this condition to the if-statements) that any of the algorithms is called only if the resulting values are not set yet. But don't worry too much about that.
From what I noticed, it seems each variable is associated with a number. You can eliminate all the possible scenarios completely and have if conditions on each of the five variables; through this identify the 3 variables first and initialize the local variables. They are independent of each other when assigned, so there's no reason to make that many combinations. This will shorten the code by a lot.
The next step is to shorten the number of combinations you have. The best thing I can think of is finding out the two values you need to compute and using the formulas, in other words another block of if else statements. Here's what the code would look like:
//initialize all to 0
double acceleration = 0;
double distance = 0;
double finalVelocity = 0;
double initVelocity = 0;
double time = 0;
//place the proper values for each
if (varEntered[0] == true){
acceleration = knownVariables[0];
}
if (varEntered[1] == true){
finalVelocity = knownVariables[1];
}
if (varEntered[2] == true){
initVelocity = knownVariables[2];
}
if (varEntered[3] == true){
distance = knownVariables[3];
}
if (varEntered[4] == true){
time = knownVariables[4];
}
// now you have 10 cases
if(varEntered[0] == false && varEntered[1] == false){
//use the formulas here
} else if (varEntered[0] == false && varEntered[2] == false){
//use other formula here
}// repeat for the next 8, with each time you change the condition and formulas
//like you have it. Also, I noticed that you missed the else in your conditionals;
//it is more efficient if you use if-else clauses when only one should execute every time you run the code.
Hope this helps.
Feel free to copy this out, fill the rest and try it out.
If you're careful with your dependencies, you can get away with 5 cases with 1 calculation each instead of 10 cases with 2 calculations each. To do this, you have to make sure that no two variables directly depend on each other. If that were to happen, then you would be out of luck when both of the variables are unknown.
One way to do this is to take your list of variables and calculate each variable in terms of the following three (wrapping around when you reach the end of the list), as in the following example. In this example, solveAll takes an array of doubles with the unknowns set to Double.MAX_VALUE, and it sets the unknowns to the correct values. (If there are more than two unknowns, you'll get an infinite recursion.)
// Really should use enum instead of constant ints, and an EnumMap instead of an array.
public final static int ACCELERATION = 0;
public final static int FINALVELOCITY = 1;
public final static int INITVELOCITY = 2;
public final static int DISTANCE = 3;
public final static int TIME = 4;
private double[] vars;
public void solveAll(double[] vars) {
this.vars = vars;
for (int i=ACCELERATION; i<=TIME; i++) {
get(i);
}
}
private double get(int v) {
if (vars[v] != Double.MAX_VALUE) {
return vars[v];
}
switch (v) {
case ACCELERATION:
return (vars[ACCELERATION] = (get(FINALVELOCITY)*get(FINALVELOCITY) - get(INITVELOCITY)*get(INITVELOCITY)) / (2*get(DISTANCE)));
case FINALVELOCITY:
return (vars[FINALVELOCITY] = 2*get(DISTANCE)/get(TIME) - get(INITVELOCITY));
case INITVELOCITY:
return (vars[INITVELOCITY] = get(DISTANCE)/get(TIME) - get(ACCELERATION)*get(TIME)/2);
case DISTANCE:
return (vars[DISTANCE] = (get(FINALVELOCITY) - get(ACCELERATION)*get(TIME)/2) * get(TIME));
case TIME:
return (vars[TIME] = (get(FINALVELOCITY) - get(INITVELOCITY)) / get(ACCELERATION));
}
return Double.MAX_VALUE; // Bad variable index
}

Categories

Resources