Coding a Math Equation - java

So I'm trying to code this equation using java:
I'm taking a, b, and c from the user.
This is the code I have so far:
import java.util.Scanner;
class QaudraticFunction{
public static void main(String []args){
Scanner input = new Scanner(System.in);
System.out.println("Enter a: ");
double a = input.nextDouble();
System.out.println("Enter b: ");
double b = input.nextDouble();
System.out.println("Enter c: ");
double c = input.nextDouble();
double val1 = (Math.pow(b,2.0)) - (4.0*a*c);
double discriminant = Math.sqrt(val1);
double val2 = (-b)-(discriminant);
double r2 = val2/(2.0*a);
System.out.println("r2 = " + r2);
}
}
I think my issue is a logical error because the program compiles and runs correctly. When I enter the values for a, b and c. I get r2 = NaN

Two possible reasons you are seeing a NaN.
The denominator is 0. This is only possible if a is set to 0 or 0.0. I'm going to assume that's not the case.
The other possibility is that you are performing a square root of a negative number, which (in java) is a NaN. See Math.sqrt javadoc for more details.
If the argument is NaN or less than zero, then the result is NaN.

Related

How to get the actual average, not rounded?

this is what I have (changed the print message for this question), and when I do 4 and 11, you should get 7.5, but it's only giving me 7. how do I fix this?
import java.util.Scanner;
class U1_L6_Average_Finder {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a;
int b;
System.out.println("put in 4");
a = scan.nextInt();
System.out.println("Put in 11");
b = scan.nextInt();
System.out.println("Here is your average");
System.out.print((a + b) / 2);
}
You could coerce the quotient to a floating-point value by changing the 2 (denominator) to a 2.0, 2f, 2.0f. If you want a double, you can use a d instead of an f.
public class AverageFloatingPointCoercionExample {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a, b;
System.out.print("Enter value #1 (4): ");
a = scan.nextInt();
System.out.print("Enter value #2 (11): ");
b = scan.nextInt();
System.out.print("Here is your average: ");
System.out.print((a + b) / 2.0f); // 7.5
}
}
Alternatively, you can cast the numerator explicitly.
System.out.print(((float) (a + b)) / 2);
You're using integers (int a, b;), so it will round your results.
Instead of it, use double or float to get what you want, e.g:
double a, b;
But, if you don't want to modify the type of your variable, you can edit your last System.out.print using f (for example), that will convert your value to float, e.g:
System.out.print((a + b) / 2.0f);
Check this to understand more about variables:
Java Variables
You have the input/averaging nailed. So here's the missing bit.
Just output r...
But if you want a certain number of decimal places (5 here)...
I did this in case you wanted to average more than 2 items...
import java.text.DecimalFormat;
class Playground {
public static void main(String[ ] args) {
int i = 5;
int j = 17;
double r = (double)i/j;
DecimalFormat df = new DecimalFormat("#.#####");
System.out.println(r);
System.out.println(df.format(r));
}
}
Outputs:
0.29411764705882354
0.29412
You are using integer divison. Integer divison will result integer as answer. You have to change one of the values to double.
Example:
System.out.println((double)(a+b)/2);
or
System.out.println((a+b)/2.0));

What am I doing wrong? I keep getting NaN? (Heron's formula)

Problem:
Write a program that reads the lengths of the sides of a triangle from the user. Compare the area of the triangle using Heron's formula, in which s represents half of the perimeter of the triangle and a,b, and c represent the lengths of the three sides.
import java.util.Scanner;
public class AreaOfTriangle
{
public static void main(String[]args)
{
Scanner scan = new Scanner(System.in);
final double NUM_ONE = 0.5;
int a, b, c;
double s, area;
System.out.print("Enter side a: ");
a = scan.nextInt();
System.out.print("Enter side b: ");
b = scan.nextInt();
System.out.print("Enter side c: ");
c = scan.nextInt();
s = NUM_ONE * (a + b + c);
area = Math.sqrt(s*(s-a)*(s-b)*(s-c));
System.out.println("\nThe area of the triangle = " + area);
}
}
The formula is correct, but s*(s-a)*(s-b)*(s-c) could end up being very slightly negative depending on the inputs (due to floating point imprecision). You should test this prior to taking the sqrt, and return zero in that instance.
Math.sqrt on a negative number will return NaN.
Because in some cases with your code you end up with a negative value in your sqrt call:
a = 1;
b = 2;
c = 5;
s = NUM_ONE * (a + b + c);
Here s = 4.0 and then your sqrt parameter is 4*3*2*-1 which is negative
Should you use Math.sqrt(Math.abs(...)) instead ?

Decimal point control

I doing a program that will print out the sum and average of a set of numbers. I'm pretty new to java, and I can't seem to figure out how to get the .7 that is supposed to be on the end of the average, I only get .0. I don't think it has to do with my math, I think there is an error in my rounding statement. Could someone point the error out to me? Thanks guys.
public class Program
{
public static void main (String[]args)
{
int a = 475;
int b = 821;
int c = 369;
int d = 562;
int e = a+b+c+d;
double f = e/4;
f=(int)(f*10+.5)/10;
System.out.println("The sum of the four numbers is "+ e + " and the average is "+ f);
}
}
Instead of double f = e/4;, do double f = e/4.0;
With e/4, you divide an int by an int, which results in an int. The result is afterwards assigned to a double. That's why you don't get decimals in your result.
With e/4.0, you divide an int by a double, which results in a double.
You lost the decimal point because e/4 is an integer. try e/4F to indicate the expression as float number
double f = e/4F;
When you have an integer divide by another integer, this is call integer division. The output will the discard the decimal values.
For example:
double v1 = 5/2; //Value of v1: 2.0 (0.5 discarded)
double v2 = 10/3; //Value of v2: 3.0 (0.333 discarded)
An integer division is happening in your codes at this line:
double f = e/4;
Hence, all the decimal values are discarded.
To retain the decimal value, you can simply do one the following (to indicate one of the operand is a decimal value, hence integer division will not occur):
double f = e/4.0;
double f = e/(double)4;
double f = e/4d;

Calculating nth root of a positive integer in Java

My task is to write a program which prompts the user to enter a positive double a and an integer
n greater than 2, and print the value of the nth root of positive integer a to the screen with accuracy to 100 places. I've used Math.pow to be able to get the root, and I feel as though I've done everything right. The only problem is that every time I run my program, the output is 1.0, no matter what numbers I input for a and n. What is the problem with my code?
import java.util.Scanner;
import java.lang.Math;
public class Q8 {
public static void main(String[] args) {
System.out.println("Enter a positive number: ");
Scanner in = new Scanner(System.in);
double a = in.nextDouble();
System.out.println("Enter an integer greater than 2: ");
Scanner in2 = new Scanner(System.in);
int n = in.nextInt();
System.out.println(pow (a,n));
}
private static double pow(double a, int n) {
if (n == 0){
return 1;
}
else{
double sum = Math.pow(a,(1/n));
return sum;
}
Why is the answer always 1.0?
Replace 1/n with 1.0/n.
You're getting integer division, so no matter what n is, if it's 2 or higher, then 1/n is coming out zero. Then you're raising your number to the zeroeth power, which gives 1.
Replacing 1 with 1.0 makes the division into a floating point division - that is, the result won't be truncated to an integer. This is what you want.
First of all, I'm assuming that
double sum = Math.pow(a,(1/root));
should be
double sum = Math.pow(a,(1/n));
since there is no root variable in your code.
Second of all, 1/n would give you 0 for every integer n > 1. Therefore sum would be 1.0.
You should replace it with :
double sum = Math.pow(a,(1.0/n));
or
double sum = Math.pow(a,(1/(double)n));
In order to get a division of double variables.

quadratic formula with scanner inputs

Okay so I am a complete Java noob, and I'm trying to create a program for class that runs a quadratic equation using scanner inputs. So far what I've got is this:
import java.util.*;
public class QuadraticFormulaSCN {
public static void main(String[]args) {
System.out.println("insert value for a:");
Scanner scan1 = new Scanner(System.in);
double a = scan1.nextDouble();
System.out.println("insert value for b:");
Scanner scan2 = new Scanner(System.in);
double b = scan2.nextDouble();
System.out.println("insert value for C:");
Scanner scan3 = new Scanner(System.in);
double c = scan3.nextDouble();
double answer =((Math.sqrt(Math.pow(b,2)-(4*a*c))-b)/2);
double final2 =(-b + Math.sqrt(Math.pow(b,2)-(4*a*c)))/2;
System.out.println("The x values are:" + answer + final2);
}
}
But I get a weird output, specifically NaNaN... What do I do to fix this? What am I doing wrong?
I'm a little late to answer, but I corrected your problems (described in the other answers), fixed one of your calculations, and cleaned up your code.
import java.util.*;
public class Test {
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Insert value for a: ");
double a = Double.parseDouble(s.nextLine());
System.out.println("Insert value for b: ");
double b = Double.parseDouble(s.nextLine());
System.out.println("Insert value for c: ");
double c = Double.parseDouble(s.nextLine());
s.close();
double answer1 = (-b + Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a);
double answer2 = (-b - Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a);
if (Double.isNaN(answer1) || Double.isNaN(answer2))
{
System.out.println("Answer contains imaginary numbers");
} else System.out.println("The values are: " + answer1 + ", " + answer2);
}
}
NaN is something you get when the calculation is invalid. Such as dividing by 0 or taking the squareroot of -1.
When I test your code with a = 1, b = 0 and c = -4 the answers is 2.02.0
The formatting is not right and the calculation of final2 is not negated.
Otherwise the code is right.
To improve you could check whether the discriminant is negative.
double d = b*b -4 * a * c;
if (d < 0){
System.out.println("Discriminant < 0, no real solutions" );
return;
}
double x1 = (-b -sqrt(d))/(2*a);
double x2 = (-b +sqrt(d))/(2*a);
System.out.format("The roots of your quadratic formula are %5.3f and %5.3f\n",x1,x2);
Or, if you prefer support for solutions from the complex domain:
if (d < 0) {
System.out.println("Discriminant < 0, only imaginary solutions");
double r = -b / (2 * a);
double i1 = -sqrt(-d) / (2 / a);
double i2 = sqrt(-d) / (2 / a);
System.out.format("The roots of your quadratic formula are (%5.3f + %5.3fi) and (%5.3f + %5.3fi)\n",r, i1, r, i2);
return;
}
You are getting NaN because you are attempting to take the square root of a negative number. In math that's not allowed unless you are allowing complex numbers, e.g. 1 +/- 2i.
This can happen in quadratic formulas when the discriminant (the thing in the square root) is negative, e.g. x^2 + 6*x + 100: b^2 - 4ac = 36 - 400 = -364. Taking the square root of a negative number in Java leads to NaN. (not a number)
To test for NaN, use Double.isNaN and handle the NaN appropriately.
In addition, your calculations are incorrect even if NaN isn't being encountered:
$ java QuadraticFormulaSCN
insert value for a:
1
insert value for b:
5
insert value for C:
6
The x values are:-2.0-2.0
This should have outputted 2.0 and 3.0
You should only do the calculation when
discriminant is equal or greater than zero
if(((Math.pow(b,2)-(4*a*c))>= 0){ /* Calculation here */ }
else {/*error message or complex number calculus*/};
One thing I always try to do is put all my math in appropriate parenthesis to avoid an, all too easy, Order of Operations mistake. The NaN is saying "Not a number." You would also get that message if the user input numbers that could not produce a result, such as a trying to get the square root of a negative number. Also, just as a note, you can save sometime by only using on Scanner for a,b, and c.
public class QuadraticFormula{
public static void main(String[] args){
java.util.Scanner input = new java.util.Scanner(System.in);
double a = input.nextDouble();
double b = input.nextDouble();
double c = input.nextDouble();
double quadPos = (-b + Math.sqrt(Math.pow(b,2)-(4*a*c)))/(2*a);
double quadNeg = (-b - Math.sqrt(Math.pow(b,2)-(4*a*c)))/(2*a);
System.out.println("-b - = " + quadNeg + "\n-b + = " + quadPos);
}
}

Categories