Calculating the average? - java

I have a method that calculates the average
Note class:
private Double moyenneFinale;
#Column(name = "moyenne_finale")
public Double getMoyenneFinale() {
return this.moyenneFinale;
}
public void setMoyenneFinale(Double moyenneFinale) {
this.moyenneFinale = moyenneFinale;
}
Class calBean
private double result;
public double moyenneFinale;
public calNote {
result=0.0
result= ((100 * 20)/100)/45;
moyenneFinale=result;
note.setMoyenneFinale(moyenneFinale);
}
//getter and setter
the result should be 0.44
but recorded in the database given value is 0.0
if I make +1 it will be 1.0

All the numeric literals at ((100 * 20)/100)/45 are integers so each operation performs integer arithmetic instead floating pointer arithmetic and finally the result is cast to double at the assignation operation.
You should change at least one of your literals to 100.0, 20.0, 45.0, ...

In line
result= ((100 * 20)/100)/45;
you are using operator / on integers. When used on integers, operator / behaves as "DIV" (resulting integer). Examples: 10/4=2, but 10.0/4=2.5, 10/4.0=2.5, 10.0/4.0=2.5.
Options are:
To set numbers as 100.0, 20.0, 100.0 and 45.0. (It is enough to set just first one to 100.0).
result= ((100.0 * 20)/100)/45;
To use casting on numbers. (double)100.
result= (((double)100 * 20)/100)/45;
Or to add 1.0* before equation;
result= 1.0*((100 * 20)/100)/45;
Tho, first method is best in your case, second and third are useful if you are given integers x, y, z, t and your result is ((x * y)/z)/t;

Related

Java decimal point in method

I am little bit lost with double decimal point at the moment.
I have basically two methods, which will set the values for double amount and double receive. Then another integer variable where I would like to set the (receive - amount) * 100.
For example if I have two double values and I want to set their difference to an int value, then would it be possible?
My problem is that if I try to find the difference between two values, then e.g. (10.0- 9.40), then it will be 0.599999999. How can I get 0.60 out of it inside the method and use it? I know how to use NumberFormat or DecimalFormat. Should I use one inside the method to set the number of decimal points?
you can round off the value im using a decimalformat to round off the number. You can pass a double variable inside the method and this will return a number rounded off to 2 decimal points.
double RoundTo2Decimals(double val) {
DecimalFormat df2 = new DecimalFormat("###.##");
return Double.valueOf(df2.format(val));
}
You can use BigDecimal to perform the rounding, or you can use maths like this. It basically multiplies by 100, rounds and divides by 100.
/**
* Performs a round which is accurate to within 1 ulp. i.e. for values very close to 0.5 it
* might be rounded up or down. This is a pragmatic choice for performance reasons as it is
* assumed you are not working on the edge of the precision of double.
*
* #param d value to round
* #return rounded value
*/
public static double round2(double d) {
final double factor = 1e2;
return d > WHOLE_NUMBER / factor || d < -WHOLE_NUMBER / factor ? d :
(long) (d < 0 ? d * factor - 0.5 : d * factor + 0.5) / factor;
}
Easiest solution could be below. Modifications and improvements are welcomed.
double x =10.0;
double y =9.40;
int xy =0;
DecimalFormat df = new DecimalFormat("#.##");
xy = (int) (Double.valueOf(df.format(x-y))*100);
System.out.println(xy);
I think I figured it out by using Math.round().
I will just ask whether my solution is a good or a bad idea to use? I am not just so familiar with BigDecimal. Long story short about the code. Example inputs are as: a = 9.40 and b = 10.0
private int difference;
private double amountDue;
private double receive;
public void setAmount(double a) {
amountDue = a;
}
public void receive(double b) {
receive = b;
difference = (int)Math.round(100 * (receive - amount));
I just needed to get int difference as 0.60 * 100 = 60, but as I mentioned before then just calculating the difference caused 0.59999999.
Just an extra question. Is it ok for me to initialize int balance variable inside one method as I have done?

Java divide operation exception

Given following codes:
long testNum = 1000;
double midNum = testNum/60000;
System.out.println(midNum);
long another = Math.round(7600/midNum);
System.out.println(another);
The output is:
0.0
9223372036854775807
Why the first output is 0.0? How could I get the right result in java?
Since the first output is 0, why the next expression has an result? Shouldn't it throw out an by zero expression?
Why the first output is 0.0?
You are using integer division so this is the right result.
How could I get the right result in java?
Don't use integer division, use floating point instead, the simplest way to to make one of the value a floating point like this.
double midNum = testNum/60000.0;
or
double midNum = testNum/60e3;
Since the first output is 0, why the next expression has an result?
Floating point arithmetic uses IEEE-754 standard (sometimes called IEEE-753.99999999999998 ;)
In floating point, you never get an exception in Java, you might get infinity, negative infinity or NaN.
Integers don't have Infinity, or NaN and have no way to represent this, so it produced an Exception.
When you round any number too big for a long it gives you the closest presentable value which is Long.MAX_VALUE
BTW
long l = Math.round(Double.POSITIVE_INFINITY); // l == Long.MAX_VALUE
long l = Math.round(Double.NEGATIVE_INFINITY); // l == Long.MIN_VALUE
long l = (long) Double.NaN; // l == 0
From Double you might find this interesting.
public final class Double extends Number implements Comparable<Double> {
/**
* A constant holding the positive infinity of type
* {#code double}. It is equal to the value returned by
* {#code Double.longBitsToDouble(0x7ff0000000000000L)}.
*/
public static final double POSITIVE_INFINITY = 1.0 / 0.0;
/**
* A constant holding the negative infinity of type
* {#code double}. It is equal to the value returned by
* {#code Double.longBitsToDouble(0xfff0000000000000L)}.
*/
public static final double NEGATIVE_INFINITY = -1.0 / 0.0;
/**
* A constant holding a Not-a-Number (NaN) value of type
* {#code double}. It is equivalent to the value returned by
* {#code Double.longBitsToDouble(0x7ff8000000000000L)}.
*/
public static final double NaN = 0.0d / 0.0;
/**
* A constant holding the largest positive finite value of type
* {#code double},
* (2-2<sup>-52</sup>)ยท2<sup>1023</sup>. It is equal to
* the hexadecimal floating-point literal
* {#code 0x1.fffffffffffffP+1023} and also equal to
* {#code Double.longBitsToDouble(0x7fefffffffffffffL)}.
*/
public static final double MAX_VALUE = 0x1.fffffffffffffP+1023; // 1.7976931348623157e+308
long is can't hold decimals. Long is equal to int just with a higher range.
You should use decimal or float.
The reason your first result is 0.0 is due to your use of implicit casting. When dividing a long by a number, Java assumes that number is of the same type and will do "long" division, which has no remainder. Since 1000/60000 is between 0 and 1, the result is effectively floored to 0, and cast to 0.0 when it's a double. You can fix this by changing a line to double midNum = testNum/60000D;
Note the "D" at the end, indicating that 60000 is a double. This will force the long to be cast as a double and give the proper result.
For the second part, you're basically dividing by a very very small number, making it appear to be quite large. 0.0 cannot be represented accurately by a double, so you're actually dividing by something slightly above 0.0, which will be fixed when you fix the other part.
use type cast operator.
double midNum = (double)testNum/60000;

Getting the decimal number of a double

I am working with a cos value which is represented in double. So my bounds are between -1.0 and 1.0, however for my work I am simply ignoring all negative variables.
Now I'd like to get the decimal number of this double number (sorry I couldn't find the literature term of this operation)
Basically with examples:
Assume that input is 0.12 then this could be written as 1.2 * 10^-1, what I am expecting to get is just the part where it is 10^-1
Another example is 0.00351, which can be written as 3.51 * 10^-3, so the expected result is 10^-3
I have developed this algorithm below but it's kind of quick and dirty. I was wondering whether is there any mathematical trick to avoid using a loop.
double result = 1;
while (input < 1.0) {
input *= 10.0;
result /= 10.0;
}
Also the above doesn't handle if input is 0.
I am using Java for coding if that helps.
It appears you are looking for the base 10 exponent of the number - use Math.log10 to do this
Math.log10(input)
e.g.
log10(100) = 2
log10(1e-5) = -5
etc.
You'll need to remember the base you've used (10 in this case)
public class Tester {
public static double lowbase(double v) {
return Math.pow(10, Math.floor(Math.log10(Math.abs(v))));
}
public static void main(String [] args){
System.out.println(lowbase(0.12));
System.out.println(lowbase(0.00351));
System.out.println(lowbase(0));
System.out.println(lowbase(-1));
}
}
Gives:
0.1
0.001
0.0
1.0
The abs is for handling the negative numbers, you may fiddle with that for a different take on negatives.
In case you are actually looking for strings such as "10^-2" (as you said that the expected result would be in this format).
public String getCientific(double input){
int exp;
exp = (int) java.lang.Math.floor(java.lang.Math.log10(input));
return "10^" + exp;
}

double precision in JAVA

I have to round off my result to the nearest fo 0.05 ie(6.34 to 6.35 and 6.37 to 6.4)
So I created myRound function.
When I wrote test to see the function, Its fails.
double rate=14.99;
double percentage=10;
double roundedCost=(rate*percentage)/100; //round off to the nearest value.
double finalRate = rate+myRound(roundedCost,2);
if(finalRate==16.49)
System.out.println("Its proper");
else
System.out.println("Wrong");
The reason is precission value of double.
How to correct the precision.
public double myRound(double value,int roundRange)
{
double hundredMultiple=(float) Math.pow(10, roundRange);
int rangeValue= (int) (value*hundredMultiple);
int tempValue= rangeValue%10;
if(tempValue<5)
tempValue=5-tempValue;
else
tempValue=10-tempValue;
rangeValue=rangeValue+tempValue;
return rangeValue/hundredMultiple;
}
The problem is that you're trying to perform operations which are interested in decimal digits. That doesn't fit well with a binary floating point type. You should use BigDecimal, which is a decimal-based representation.
Just as an idea of why your current scheme won't work, if you write:
double d = 0.1;
the value of d isn't actually 0.1 - it's the closest 64-bit IEEE 754 binary floating point value to 0.1. It'll be very close in value to 0.1, but it won't be 0.1.
A much shorter function is to do.
public static double round(double v, int precision) {
long t = TENS[precision]; // contains powers of ten.
return (double) (long) (v > 0 ? v * t + 0.5 : v * t - 0.5) / t;
}
This works for numbers with less than 18 significant digits (over your precision) e.g. for 2 decimal places, the number should be less than 10^16.
BTW, You should always round the final answer (possibly only round the final answer). This is because x + round(y, 2) may not be equal to round(x + y, 2)

How do you test to see if a double is equal to NaN?

I have a double in Java and I want to check if it is NaN.
What is the best way to do this?
Use the static Double.isNaN(double) method, or your Double's .isNaN() method.
// 1. static method
if (Double.isNaN(doubleValue)) {
...
}
// 2. object's method
if (doubleObject.isNaN()) {
...
}
Simply doing:
if (var == Double.NaN) {
...
}
is not sufficient due to how the IEEE standard for NaN and floating point numbers is defined.
Try Double.isNaN():
Returns true if this Double value is a Not-a-Number (NaN), false otherwise.
Note that [double.isNaN()] will not work, because unboxed doubles do not have methods associated with them.
You might want to consider also checking if a value is finite via Double.isFinite(value). Since Java 8 there is a new method in Double class where you can check at once if a value is not NaN and infinity.
/**
* Returns {#code true} if the argument is a finite floating-point
* value; returns {#code false} otherwise (for NaN and infinity
* arguments).
*
* #param d the {#code double} value to be tested
* #return {#code true} if the argument is a finite
* floating-point value, {#code false} otherwise.
* #since 1.8
*/
public static boolean isFinite(double d)
You can check for NaN by using var != var. NaN does not equal NaN.
EDIT: This is probably by far the worst method. It's confusing, terrible for readability, and overall bad practice.
If your value under test is a Double (not a primitive) and might be null (which is obviously not a number too), then you should use the following term:
(value==null || Double.isNaN(value))
Since isNaN() wants a primitive (rather than boxing any primitive double to a Double), passing a null value (which can't be unboxed to a Double) will result in an exception instead of the expected false.
The below code snippet will help evaluate primitive type holding NaN.
double dbl = Double.NaN;
Double.valueOf(dbl).isNaN() ? true : false;
Beginners needs practical examples. so try the following code.
public class Not_a_Number {
public static void main(String[] args) {
String message = "0.0/0.0 is NaN.\nsimilarly Math.sqrt(-1) is NaN.";
String dottedLine = "------------------------------------------------";
Double numerator = -2.0;
Double denominator = -2.0;
while (denominator <= 1) {
Double x = numerator/denominator;
Double y = new Double (x);
boolean z = y.isNaN();
System.out.println("y = " + y);
System.out.println("z = " + z);
if (z == true){
System.out.println(message);
}
else {
System.out.println("Hi, everyone");
}
numerator = numerator + 1;
denominator = denominator +1;
System.out.println(dottedLine);
} // end of while
} // end of main
} // end of class

Categories

Resources