My question may seem simple, but still can not get something that works.
I need to customize the Math.round rounding format or something to make it work as follows:
If the number is 1.6 he should round to 1, if greater than or equal to 1.7 should round to 2.0 . And so to all other decimal results with # .6
The way I'm doing the 1.6 being rounded to 2 shall be rounded to 1.
How can I do that?
Thank you!
Simply do this:
double threshold = 0.7;
Math.round(x - threshold + 0.5);
You could write a method that takes a double variable as input and returns the integer based on the first digit after the point. For instance, you could convert the input to a String and delimit it at the decimal point. Then check if the first digit after the point is less or greater than 6.
Math.floor(x + 0.6);
It possibly may solve your question.
Related
I'm wondering what the best way to fix precision errors is in Java. As you can see in the following example, there are precision errors:
class FloatTest
{
public static void main(String[] args)
{
Float number1 = 1.89f;
for(int i = 11; i < 800; i*=2)
{
System.out.println("loop value: " + i);
System.out.println(i*number1);
System.out.println("");
}
}
}
The result displayed is:
loop value: 11
20.789999
loop value: 22
41.579998
loop value: 44
83.159996
loop value: 88
166.31999
loop value: 176
332.63998
loop value: 352
665.27997
loop value: 704
1330.5599
Also, if someone can explain why it only does it starting at 11 and doubling the value every time. I think all other values (or many of them at least) displayed the correct result.
Problems like this have caused me headache in the past and I usually use number formatters or put them into a String.
Edit: As people have mentioned, I could use a double, but after trying it, it seems that 1.89 as a double times 792 still outputs an error (the output is 1496.8799999999999).
I guess I'll try the other solutions such as BigDecimal
If you really care about precision, you should use BigDecimal
https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html
https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/math/BigDecimal.html
The problem is not with Java but with the good standard float's (http://en.wikipedia.org/wiki/IEEE_floating-point_standard).
You can either:
use Double and have a bit more precision (but not perfect of course, it also has limited precision)
use a arbitrary-precision-library
use numerically stable algorithms and truncate/round digits of which you are not sure they are correct (you can calculate numeric precision of operations)
When you print the result of a double operation you need to use appropriate rounding.
System.out.printf("%.2f%n", 1.89 * 792);
prints
1496.88
If you want to round the result to a precision, you can use rounding.
double d = 1.89 * 792;
d = Math.round(d * 100) / 100.0;
System.out.println(d);
prints
1496.88
However if you see below, this prints as expected, as there is a small amount of implied rounding.
It worth nothing that (double) 1.89 is not exactly 1.89 It is a close approximation.
new BigDecimal(double) converts the exact value of double without any implied rounding. It can be useful in finding the exact value of a double.
System.out.println(new BigDecimal(1.89));
System.out.println(new BigDecimal(1496.88));
prints
1.8899999999999999023003738329862244427204132080078125
1496.8800000000001091393642127513885498046875
Most of your question has been pretty well covered, though you might still benefit from reading the [floating-point] tag wiki to understand why the other answers work.
However, nobody has addressed "why it only does it starting at 11 and doubling the value every time," so here's the answer to that:
for(int i = 11; i < 800; i*=2)
╚═══╤════╝ ╚╤═╝
│ └───── "double the value every time"
│
└───── "start at 11"
You could use doubles instead of floats
If you really need arbitrary precision, use BigDecimal.
first of Float is the wrapper class for the primitive float
and doubles have more precision
but if you only want to calculate down to the second digit (for monetary purposes for example) use an integer (as if you are using cents as unit) and add some scaling logic when you are multiplying/dividing
or if you need arbitrary precision use BigDecimal
If precision is vital, you should use BigDecimal to make sure that the required precision remains. When you instantiate the calculation, remember to use strings to instantiate the values instead of doubles.
I never had a problem with simple arithmetic precision in either Basic, Visual Basic, FORTRAN, ALGOL or other "primitive" languages. It is beyond comprehension that JAVA can't do simple arithmetic without introducing errors. I need just two digits to the right of the decimal point for doing some accounting. Using Float subtracting 1000 from 1355.65 I get 355.650002! In order to get around this ridiculous error I have implemented a simple solution. I process my input by separating the values on each side of the decimal point as character, convert each to integers, multiply each by 1000 and add the two back together as integers. Ridiculous but there are no errors introduced by the poor JAVA algorithms.
This is the first code I've ever written. Here's a part of my code which is meant to calculate the side lengths of a cube and tetrahedron after the user gives a value for the volume, however The output is incorrect. I'm pretty sure I have the equations correct, maybe I'm using the Math.pow method incorrectly?
System.out.println("Now, please enter a volume for side or diameter calculation, then press ENTER: ");
volume = input.nextDouble();
cubeSide = Math.pow(volume, (1/3));
sphereDiameter = Math.pow(volume / PI * 6, (1/3));
tetSide = SQRT_2 * Math.pow(3 * volume, (1/3));
System.out.println("");
System.out.println("The Side of your CUBE is : " + cubeSide);
System.out.println("");
System.out.println("The Diameter of your SPHERE is : " + sphereDiameter);
System.out.println("");
System.out.println("The Side of your TETRAHEDRON is : " + tetSide);
Any ideas on how to get correct outputs?
1/3 is 0 - when both dividend and divisor are integral, / performs integral division. You want 1.0 / 3 or 1 / 3.0 or 1.0 / 3.0, which evaluate to 0.3333333-ish.
Your question is an instance of this one Division of integers in Java
Bassically, you need to cast the 1/3 part of your Math.pow() to double, because if you don't do that for default it will take the result as an Integer (always 0).
For example:
double volume = 15.34;
double fraction = (double) 1/3;
double cubeSide = Math.pow(volume,fraction);
System.out.println(cubeSide);
Output is
2.4847066359757295
Otherwise output is always 1.0. Which is the result of any number rised to the zero.
As stated in your comment, when the input is:
1000
the output should be a whole:
10
But actually its:
9.999999999999998
The simplest solution to that could be just:
float roundedValue = Math.round(cubeSide);
And say: that's not my problem. But we want to understand what that's happening. As most things in this world, you are not the first one to face this problem. Let's do some research and find that there in StackOverFlow it have been asked:
Floating point arithmetic not producing exact results
Is floating point math broken?
In the first link, its suggested to read What Every Computer Scientist Should Know About Floating-Point Arithmetic.
I wont repeat what those wise people whom know a lot more than me said, so I highly recommend to you to read the above links.
For example if I do this:
double decPart = 5.57 - 5;
System.out.println(decPart);
it returns 0.5700000000000003, instead of just 0.57. I can print it out properly using System.out.printf("%.2f", decPart), but that doesn't solve the problem (Note: the decimal part is not necessarily 2 decimal places). So for example if I try to do this:
System.out.println(1.0 - decPart);
it would return 0.4299999999999997
Can somebody please explain this behavior and how to fix it. Thanks in advance.
This is due to floating point imprecision. Floating-point numbers (float, double in Java) cannot represent some numbers exactly. If you're looking for absolute precision, look into BigDecimal.
I have weird decimal calculation that really surprise me, I have two big decimal number, one is a normal proce and the other one is an offer price. Then I want to calculate discount percentage and ceil it to the nearest integer.
Here are the code:
BigDecimal listPrice = new BigDecimal(510000);
BigDecimal offerPrice = new BigDecimal(433500);
int itemDiscount = (int)Math.ceil(((listPrice.longValue() - offerPrice.longValue()) / (float) listPrice.longValue()) * 100);
I expect it would set 15 as value of itemDiscount, but surprisingly it has 16, wow. Then i print each calculation to show in which statement is the problem, so i put System.out.println for each statement as below :
System.out.println(listPrice.longValue() - offerPrice.longValue()); //==> show 76500
System.out.println((listPrice.longValue() - offerPrice.longValue()) / (float) listPrice.longValue()); // ==> 0.15
System.out.println((listPrice.longValue() - offerPrice.longValue()) * 100 / (float) listPrice.longValue()); // ==> 15.000001
the problem is in above statement, istead of returning 15.0, it return 15.000001. And when i ceil it, it will of course return 16 instead of 15.
What is the explanation if this case? is this the way it is or it is a bug?
What is the explanation if this case? is this the way it is or it is a bug?
It is the way it is. It is not a bug.
You are doing the calculation using floating point types (float) and floating point arithmetic is imprecise.
I'm not sure what the best fix is here. Maybe doing the computation using BigDecimal arithmetic methods would give a better result, but it is by no means guaranteed that you won't get similar problems in this calculation with different inputs ...
However, I suspect that the real problem is that you should not be using ceil in that calculation. Even BigDecimal will give you rounding errors; e.g. if your computation involves dividing by 3, the intermediate result cannot be precisely represented using a base-10 representation.
The correct way to do calculations using Real numbers is to properly take account of the error bars in the calculation.
Try using the divide method directly from the BigDecimal class. If you are casting to a float then you are not using the benefit of BigDecimal .
http://www.roseindia.net/java/java-bigdecimal/bigDecimal-divide-int.shtml
How to round up a decimal number to a whole number.
3.50 => 4
4.5 => 5
3.4 => 3
How do you do this in Java? Thanks!
With the standard rounding function? Math.round()
There's also Math.floor() and Math.ceil(), depending on what you need.
You can use
int i = Math.round(f);
long l = Math.round(d);
where f and d are of type float and double, respectively.
And if you're working with only positive numbers, you can also use int i = (int)(d + 0.5).
EDIT: if you want to round negative numbers up (towards positive infinity, such that -5.4 becomes -5, for example), you can use this as well. If you want to round to the higher magnitude (rounding -5.4 to -6), you would be well advised to use some other function put forth by another answer.
Java provides a few functions in the Math class to do this. For your case, try Math.ceil(4.5) which will return 5.
new BigDecimal(3.4);
Integer result = BigDecimal.ROUND_HALF_UP;
Or
Int i = (int)(202.22d);
Using Math.max you can do it like this:
(int) Math.max(1, (long) Math.ceil((double) (34) / 25)
This would give you 2