Compute average of two double? - java

I am trying compute average of two double value, but it dose not work truly. I think it is "rounding error" am I right? and how can I fix it?
point.get(0)=1
point.get(1)=4
double Average = (double)(point.get(0) + point.get(1) / 2);
Output:
Average: 3.0
Why?

double Average = (double)(point.get(0) + point.get(1) / 2);
is executed as
Average = (double)(1 + 4/2) = (double) (1+2) = 3.0
Problem
Divison(/) has higher precedence than addition(+)
Fix
You need to add brackets for proper calculation:
double Average = (double)((point.get(0) + point.get(1)) / 2);
should execute as:
Average = (double)((1 + 4)/2) = (double) (5/2) = 2.5

double Average = (double)(point.get(0) + point.get(1) / 2)
Operator precedence trouble. Try this:
double Average = (point.get(0) + point.get(1)) / 2.0;

This has to do with the order of operators - the / has a higher precedence than +, so you are actually getting 1 + (4/2) which does equal 3.
Try this instead:
double Average = (double)((point.get(0) + point.get(1)) / 2);
The extra brackets will correct your issue.

Division takes precedence over addition. Hence,
Average = (double)(1 + 4/2) = (double) (1+2) = 3.0
You should probably make it more like
Average = (double)((1+4)/2)

Related

how to get double to round up to nearest integer?

the prompt says "Write a program which takes two doubles as input, then prints the sum of the numbers when they are both rounded to their nearest whole number. You may assume the double input is always positive."
what i wrote:
Scanner scan = new Scanner(System.in);
System.out.print("Please input two decimal numbers:");
double hit_1 = scan.nextDouble();
double hit_2 = scan.nextDouble();
double hit_add = (hit_1 + hit_2 + 0.5);
System.out.print("Answer: " + (int)hit_1 + " + " + (int)hit_2 + " = " + (int)hit_add);
for most decimals, it rounds fine, but what i want is for numbers like 4.5 to round to 5. right now, it rounds 4.5 to 4. i added 0.5 in an attempt to get the double to round up, but it didn't work. i'm also not allowed to use Math.round() or anything like that.
create your own round method like this.
Convert to int, then find the remainder.
If remainder >= 0.5, just add 1 to the integer. See below:
private static int round(double d){
int i = (int)d;
double remainder = d - i;
if(remainder>=0.5){
i++;
}
return i;
}
then you can use that method on your double
just need +0.5:
double a = 1.8, b = 1.2;
System.out.println((int)(a + 0.5));
System.out.println((int)(b + 0.5));
System.out.println((int)(a + 0.5) + (int)(b + 0.5));
for your code:
Scanner scan = new Scanner(System.in);
System.out.print("Please input two decimal numbers:");
double hit_1 = scan.nextDouble() + 0.5;
double hit_2 = scan.nextDouble() + 0.5;
int hit_1P2 = (int)hit_1 + (int)hit_2;
System.out.print("Answer: " + (int)hit_1 + " + " + (int)hit_2 + " = " + hit_1P2);
There was two ways where double can be rounded off to nearest integer.
a. Using typecasting to int
Example : If double holds value as 3.26, all the digits after decimal are lost.
b. Using Math.round() function - This will add 0.5 to double and rounds to nearest integer.
Example : If double holds value of 3.7, then this function will add 0.5 and rounds to 4 as nearest integer.
Similar way, if double value is 3.2, then Math.round() will add 0.5, so this would become 3.7, in this case the nearest integer is still 3
Below is sample code block for above two examples
double d = 3.5;
int typeCastInt = (int) d;
int t = (int) Math.round(d);
System.out.println(typeCastInt); //prints 3
System.out.println(t); //Prints 4

Java - Issue with Type Conversion in Expressions

I am just starting out with Java and practicing some sample programs. Below is the code i am trying out.
/*
Using a cast
*/
class UseCast {
public static void main(String agrs[]) {
int i;
double d;
for (i = 0; i < 5; i++) {
System.out.println(i + " / 3 with cast to double is " + (double) i
/ 3);
// > Why is the parenthesis around (i / 3) changing the result
System.out.println(i + " / 3 with cast to double is "
+ (double) (i / 3));
System.out.println();
}
}
}
The first output works as expected.
In the second output, (i / 3) seems to be evaluated first as integer and then getting promoted to double for printing. What if i want to evaluate the expression as double and still retain the parenthesis around i / 3. How to do that?
You should probably be doing something like below without even typecasting:
System.out.println(i + " / 3 with cast to double is "
+ (i / 3d));
For your case you are right, its int/int division and then you are type casting to double which doesn't makes any difference.
You can of course do
((double) i / 3)
If you insist to keep the cast outside the whole expression, you can multiply one of i or 3 by 1.0:
(double) (i * 1.0 / 3)
But now the cast is redundant since the expression is already evaluated to a double.
The result you're getting is because numbers are int by default in Java,
i / 3 will be calculated according to int-calculations, when having the result (0), the cast will be applied.
int/int is considered as integer division, giving you integer result.
Either of the numerator or denominator has to be double to give you decimal answer.
The simplest way to do it is as follow:
(i / 3.0)
(int / int ) the division here will be considered as integer division
(int / dbl) or (dbl/int) or (dbl/dbl) the division here will be considered as floating point division.

How do I format double input in Java WITHOUT rounding it?

I have read this question Round a double to 2 decimal places It shows how to round number. What I want is just simple formatting, printing only two decimal places.
What I have and what I tried:
double res = 24.695999999999998;
DecimalFormat df = new DecimalFormat("####0.00");
System.out.println("Value: " + df.format(res)); //prints 24.70 and I want 24.69
System.out.println("Total: " + String.format( "%.2f", res )); //prints 24.70
So when I have 24.695999999999998 I want to format it as 24.69
You need to take the floor of the double value first - then format it.
Math.floor(double)
Returns the largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer.
So use something like:
double v = Math.floor(res * 100) / 100.0;
Other alternatives include using BigDecimal.
public void test() {
double d = 0.29;
System.out.println("d=" + d);
System.out.println("floor(d*100)/100=" + Math.floor(d * 100) / 100);
System.out.println("BigDecimal d=" + BigDecimal.valueOf(d).movePointRight(2).round(MathContext.UNLIMITED).movePointLeft(2));
}
prints
d=0.29
floor(d*100)/100=0.28
BigDecimal d=0.29
Multiply the number by 100 and cast it to an integer. This cuts off all the decimal spaces except the two you want. Divide the result by 100.00. (24.69).
int temp = (int)(res * 100);
double result = temp / 100.00;
or the same thing in one line of code:
double result = ((int)(res * 100)) / 100.00;
In addition to using Math.floor(double) and calculating a scale (e.g. * 100 and then / 100.0 for two decimal points) you could use BigDecimal, then you can invoke setScale(int, int) like
double res = 24.695999999999998;
BigDecimal bd = BigDecimal.valueOf(res);
bd = bd.setScale(2, RoundingMode.DOWN);
System.out.println("Value: " + bd);
Which will also give you (the requested)
Value: 24.69

Raising a number to a power in Java

Here is my code. For some reason my BMI is not calculated correctly.
When I check the output on a calculator for this : (10/((10/100)^2))) I get 1000, but in my program, I get 5. I'm not sure what I am doing wrong. Here is my code:
import javax.swing.*;
public class BMI {
public static void main(String args[]) {
int height;
int weight;
String getweight;
getweight = JOptionPane.showInputDialog(null, "Please enter your weight in Kilograms");
String getheight;
getheight = JOptionPane.showInputDialog(null, "Please enter your height in Centimeters");
weight = Integer.parseInt(getweight);
height = Integer.parseInt(getheight);
double bmi;
bmi = (weight/((height/100)^2));
JOptionPane.showMessageDialog(null, "Your BMI is: " + bmi);
}
}
^ in java does not mean to raise to a power. It means XOR.
You can use java's Math.pow()
And you might want to consider using double instead of int—that is:
double height;
double weight;
Note that 199/100 evaluates to 1.
we can use
Math.pow(2, 4);
this mean 2 to the power 4 (2^4)
answer = 16
^ is not the operator you want. You are looking for the pow method of java.lang.Math.
You can use Math.pow(value, power).
Example:
Math.pow(23, 5); // 23 to the fifth power
Your calculation is likely the culprit. Try using:
bmi = weight / Math.pow(height / 100.0, 2.0);
Because both height and 100 are integers, you were likely getting the wrong answer when dividing. However, 100.0 is a double. I suggest you make weight a double as well. Also, the ^ operator is not for powers. Use the Math.pow() method instead.
Too late for the OP of course, but still...
Rearranging the expression as:
int bmi = (10000 * weight) / (height * height)
Eliminates all the floating point, and converts a division by a constant to a multiplication, which should execute faster. Integer precision is probably adequate for this application, but if it is not then:
double bmi = (10000.0 * weight) / (height * height)
would still be an improvement.
You should use below method-
Math.pow(double a, double b)
From (https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#pow-double-double-)
Returns the value of the first argument raised to the power of the second argument.
int weight=10;
int height=10;
double bmi;
bmi = weight / Math.pow(height / 100.0, 2.0);
System.out.println("bmi"+(bmi));
double result = bmi * 100;
result = Math.round(result);
result = result / 100;
System.out.println("result"+result);
1) We usually do not use int data types to height, weight, distance,
temperature etc.(variables which can have decimal points)
Therefore height, weight should be double or float.
but double is more accurate than float when you have more decimal points
2) And instead of ^, you can change that calculation as below using Math.pow()
bmi = (weight/(Math.pow(height/100, 2)));
3) Math.pow() method has below definition
Math.pow(double var_1, double var_2);
Example:
i) Math.pow(8, 2) is produced 64 (8 to the power 2)
ii) Math.pow(8.2, 2.1) is produced 82.986813689753 (8.2 to the power 2.1)
I did the benchmarking with Math.pow(x,2) and x*x,
the result is that Math.pow() is easily forty times slower than manually multiplying it by itself, so i don't recommend it for anything where a little bit of performance is required.
Here's the results:
proof_of_work: 19.284756867003345
time for Math.pow(x,2) in ns: 35143
proof_of_work: 19.284756867003345
time for x*x in ns: 884
manual calculation is 39 times faster
and here's the test-code
double r1 = 4.391441320;
long multiply_d1 = System.nanoTime();
double multiply_dr = Math.pow(r1,2);
long multiply_d2 = System.nanoTime();
System.out.println(("proof_of_work: ") + (multiply_dr));
System.out.println(("time for Math.pow(x,2) in ns: ") + (multiply_d2 - multiply_d1));
long multiply_t1 = System.nanoTime();
double multiply_tr = r1*r1;
long multiply_t2 = System.nanoTime();
System.out.println(("proof_of_work: ") + (multiply_tr));
System.out.println(("time for x*x in ns: ") + (multiply_t2 - multiply_t1));
System.out.println(("manual calculation is ") + ((multiply_d2 - multiply_d1) / (multiply_t2 - multiply_t1)) + (" times faster"));
Most efficient solution is
public Float fastPow(Float number, Integer power) {
if (power == 0) {
return 1.0f;
} else if (power % 2 == 1) {
return fastPow(number, power - 1) * number;
} else {
return fastPow(number * number, power / 2);
}
}
Let A is our number and N our power. Then A^2^N = (A^2)^N. And A^N = (A^2)^N/2. The function above reflects this relationship.

Java: Implementing simple equation

I am looking to implement the simple equation:
i,j = -Q ± √(Q2-4PR) / 2P
To do so I have the following code (note: P = 10. Q = 7. R = 10):
//Q*Q – 4PR = -351 mod 11 = -10 mod 11 = 1, √1 = 1
double test = Math.sqrt(modulo(((Q*Q) - ((4*P)*R))));
// Works, but why *-10 needed?
i = (int)(((-Q+test)/(P*2))*-10); // i = 3
j = (int)(((-Q-test)/(P*2))*-10); // j = 4
To put it simply, test takes the first part of the equation and mods it to a non-zero integer in-between 0 and 11, then i and j are written. i and j return the right number, but for some reason *-10 is needed to get them right (a number I guessed to get the correct values).
If possible, I'd like to find a better way of performing the above equation because my way of doing it seems wrong and just works. I'd like to do it as the equation suggests, rather than hack it to work.
The quadratic equation is more usually expressed in terms of a, b and c. To satisfy ax2+bx+c = 0, you get (-b +/- sqrt(b^2-4ac)) / 2a as answers.
I think your basic problem is that you're using modulo for some reason instead of taking the square root. The factor of -10 is just a fudge factor which happens to work for your test case.
You should have something like this:
public static void findRoots(double a, double b, double c)
{
if (b * b < 4 * a * c)
{
throw new IllegalArgumentException("Equation has no roots");
}
double tmp = Math.sqrt(b * b - 4 * a * c);
double firstRoot = (-b + tmp) / (2 * a);
double secondRoot = (-b - tmp) / (2 * a);
System.out.println("Roots: " + firstRoot + ", " + secondRoot);
}
EDIT: Your modulo method is currently going to recurse pretty chronically. Try this instead:
public static int modulo(int x)
{
return ((x % 11) + 11) % 11;
}
Basically the result of the first % 11 will be in the range [-10, 10] - so after adding another 11 and taking % 11 again, it'll be correct. No need to recurse.
At that point there's not much reason to have it as a separate method, so you can use:
public static void findRoots(double a, double b, double c)
{
int squareMod11 = (((b * b - 4 * a * c) % 11) + 11) % 11;
double tmp = Math.sqrt(squareMod11);
double firstRoot = (-b + tmp) / (2 * a);
double secondRoot = (-b - tmp) / (2 * a);
System.out.println("Roots: " + firstRoot + ", " + secondRoot);
}
You need to take the square root. Note that Q^2-4PR yields a negative number, and consequently you're going to have to handle complex numbers (or restrict input to avoid this scenario). Apache Math may help you here.
use Math.sqrt for the square root. Why do you cast i and j to ints? It is equation giving you roots of square function, so i and j can be any complex numbers. You shall limit the discriminant to positive-only values for real (double) roots, otherwise use complex numbers.
double test = Q*Q - 4*P*R;
if(Q < 0) throw new Exception("negative discriminant!");
else {
test = Math.sqrt(test);
double i = (-Q + test) / 2*P;
double i = (-Q - test) / 2*P;
}
Why are you doing modulo and not square root? Your code seems to be the way to get the roots of a quadratic equation ((a±sqrt(b^2-4ac))/2a), so the code should be:
double delta = Q*Q-4*P*R);
if(delta < 0.0) {
throw new Exception("no roots");
}
double d = Math.power(delta,0.5);
double r1 = (Q + d)/(2*P)
double r2 = (Q - d)/(2*P)
As pointed out by others, your use of mod isn't even wrong. Why are you making up mathematics like this?
It's well known that the naive solution to the quadratic equation can have problems if the value of b is very nearly equal to the discriminant.
A better way to do it is suggested in section 5.6 of "Numerical Recipes in C++": if we define
(source: equationsheet.com)
Then the two roots are:
and
Your code also needs to account for pathological cases (e.g., a = 0).
Let's substitute your values into these formulas and see what we get. If a = 10, b = 7, and c = 10, then :
(source: equationsheet.com)
Then the two roots are:
(source: equationsheet.com)
and
(source: equationsheet.com)
I think I have the signs right.
If your calculation is giving you trouble, it's likely due to the fact that you have complex roots that your method can't take into account properly. You'll need a complex number class.

Categories