I am dividing two ints x/y,. Say 3/2. Then one would get 1 as result though the actual result is 1.5. Ok this is obvious as it's int division. But I want 1.5 to be rounded off to the next highest int not the immediate lowest. So 2 is desired as result. (One can write simple logic using mod and then division... But am looking for simple Java based API). Any thoughts?
You can, in general, write (x + y - 1) / y to get the rounded-up version of x/y. If it's 3/2, then that becomes (3 + 2 - 1) / 2 = 4 / 2 = 2.
You can use the ceil (ceiling) function:
https://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#ceil(double)
That will essentially round up to the nearest whole number.
If you can change the datatype to double, following is the best solution -
double x = 3;
double y = 2;
Math.ceil(Math.abs(x/y));
This will give you 2.0
import java.lang.Math;
//round Up Math.ceil(double num)
//round Down Math.floor(double num)
public class RoundOff
{
public static void main(String args[])
{ //since ceil() method takes double datatype value as an argument
//either declare at least one of this variable as double
int x=3;
int y=2; //double y =2;
//or at least cast one of this variable as a (double) before taking division
System.out.print(Math.ceil((double)x/y)); //prints 2.0
//System.out.print(Math.ceil(x/y));
}
}
Related
I need to cast a double to an int in Java, but the numerical value must always round down. i.e. 99.99999999 -> 99
Casting to an int implicitly drops any decimal. No need to call Math.floor() (assuming positive numbers)
Simply typecast with (int), e.g.:
System.out.println((int)(99.9999)); // Prints 99
This being said, it does have a different behavior from Math.floor which rounds towards negative infinity (#Chris Wong)
To cast a double to an int and have it be rounded to the nearest integer (i.e. unlike the typical (int)(1.8) and (int)(1.2), which will both "round down" towards 0 and return 1), simply add 0.5 to the double that you will typecast to an int.
For example, if we have
double a = 1.2;
double b = 1.8;
Then the following typecasting expressions for x and y and will return the rounded-down values (x = 1 and y = 1):
int x = (int)(a); // This equals (int)(1.2) --> 1
int y = (int)(b); // This equals (int)(1.8) --> 1
But by adding 0.5 to each, we will obtain the rounded-to-closest-integer result that we may desire in some cases (x = 1 and y = 2):
int x = (int)(a + 0.5); // This equals (int)(1.8) --> 1
int y = (int)(b + 0.5); // This equals (int)(2.3) --> 2
As a small note, this method also allows you to control the threshold at which the double is rounded up or down upon (int) typecasting.
(int)(a + 0.8);
to typecast. This will only round up to (int)a + 1 whenever the decimal values are greater than or equal to 0.2. That is, by adding 0.8 to the double immediately before typecasting, 10.15 and 10.03 will be rounded down to 10 upon (int) typecasting, but 10.23 and 10.7 will be rounded up to 11.
(int)99.99999
It will be 99.
Casting a double to an int does not round, it'll discard the fraction part.
Math.floor(n)
where n is a double. This'll actually return a double, it seems, so make sure that you typecast it after.
This works fine int i = (int) dbl;
new Double(99.9999).intValue()
try with this, This is simple
double x= 20.22889909008;
int a = (int) x;
this will return a=20
or try with this:-
Double x = 20.22889909008;
Integer a = x.intValue();
this will return a=20
or try with this:-
double x= 20.22889909008;
System.out.println("===="+(int)x);
this will return ===20
may be these code will help you.
Try using Math.floor.
In this question:
1.Casting double to integer is very easy task.
2.But it's not rounding double value to the nearest decimal. Therefore casting can be done like this:
double d=99.99999999;
int i=(int)d;
System.out.println(i);
and it will print 99, but rounding hasn't been done.
Thus for rounding we can use,
double d=99.99999999;
System.out.println( Math.round(d));
This will print the output of 100.
I am trying to create a recursive method to compute a series in java 1/i.
Here is my code:
public static double computeSeries(int n) {
if (n == 1)
return 1;
else
return (1/n) + computeSeries(n - 1);
}
where 'n' is passed through the main method. However it doesn't exactly work correctly. FE when I type in 3, it returns 2.0, where I calculated it to be 1.8, and if I use 2, it gives me 1.0
While you're going to work with decimals, you might at least want to have a double as input
Solution
public static double computeSeries(double n)
However, if you only want the method to have an int as input, you might want to change 1/n to 1.0/n this will result to an operation of type double instead of int
This is called Promotion
JLS §5.6.2
If either operand is of type double, the other is converted to double.
First part of your result (1/n) is truncated to an int:
return (1/n) + computeSeries(n - 1);
Force calculations to be done in a double type by changing 1 to 1.0 (then it's a double):
return (1.0/n) + computeSeries(n - 1);
1/n
You are calculating in integers. This is always ZERO unless n == 1
Your first division will be 0 in most of the cases, since you're calculating with integers.
Instead use one of
return (1.0 / n) + computeSeries(n - 1);
return (1 / (double) n) + computeSeries(n - 1);
public static double computeSeries(double n) {
Bonus: You should take care of n = 0 to prevent a java.lang.ArithmeticException.
As most others have said, you need to convert the values to double before performing operations. Also, and this may just be personal preference, you may not want to have n calls of computeSeries running before they can all be completed.
Edit: After thinking more, using the for loop as I did below, there is no need for an extra method to calculate each term in the series. You can simply do the following
public static double computeSeries(int n) {
double sum = 0.0;
for(int i=1; i<=n; i++){
sum += (1.0/(double)i);
}
return sum;
}
I am new to Java and I would like to know why when you have double 10/4 you get 2? Does double always have to have decimals in order to get the right answer? Thanks.
public class Super {
public static void main(String[] args){
double x = 10/4;
System.out.println(x);
}
}
You are performing integer division before assigning the result. Integer division results in an int, the truncated result 2. To force floating point calculation and get 2.5, use double literals:
double x = 10.0 / 4.0;
or cast one to a double:
double x = (double) 10 / 4;
You are dividing with integers. You can declare those as doubles the following way (or use f for floats):
double x = 10d/4d;
System.out.println(x);
Integer division. Even though you're assigning the result to a double, you're still dividing two integers (10 and 4) so you get an integer result (floor of the actual result).
You can fix this by having one or both operands be a floating point value, for example like this:
double x = 10.0/4;
or by using type casting:
double x = (double)10/4;
Replace it by:
double x = 10.0/4.0;
Double always takes in a decimal. So it would have to be
public class Super {
public static void main(String[] args){
double x = 10.0/4.0;
System.out.println(x);
}
}
For double you need to use the following
10d/4d
Then the output is going to be 2.5 Otherwise you are just gonna end up diving two integers
The right side ofter the '=' is an integer expression, which gets converted to double only after it's calculated. So it calculates 10/4 as an integer, 2, and then converts that number to double. If you want it as a double from the beginning you have to write
double x = 10.0 / 4.0;
Only numbers that cannot be read as integer will be treated as double. Or even simpler
double x = 2.5; // :-)
int total = (int) Math.ceil(157/32);
Why does it still return 4? 157/32 = 4.90625, I need to round up, I've looked around and this seems to be the right method.
I tried total as double type, but get 4.0.
What am I doing wrong?
You are doing 157/32 which is dividing two integers with each other, which always result in a rounded down integer. Therefore the (int) Math.ceil(...) isn't doing anything. There are three possible solutions to achieve what you want. I recommend using either option 1 or option 2. Please do NOT use option 0.
Option 0
Convert a and b to a double, and you can use the division and Math.ceil as you wanted it to work. However I strongly discourage the use of this approach, because double division can be imprecise. To read more about imprecision of doubles see this question.
int n = (int) Math.ceil((double) a / b));
Option 1
int n = a / b + ((a % b == 0) ? 0 : 1);
You do a / b with always floor if a and b are both integers. Then you have an inline if-statement which checks whether or not you should ceil instead of floor. So +1 or +0, if there is a remainder with the division you need +1. a % b == 0 checks for the remainder.
Option 2
This option is very short, but maybe for some less intuitive. I think this less intuitive approach would be faster than the double division and comparison approach:
Please note that this doesn't work for b < 0.
int n = (a + b - 1) / b;
To reduce the chance of overflow you could use the following. However please note that it doesn't work for a = 0 and b < 1.
int n = (a - 1) / b + 1;
Explanation behind the "less intuitive approach"
Since dividing two integers in Java (and most other programming languages) will always floor the result. So:
int a, b;
int result = a/b (is the same as floor(a/b) )
But we don't want floor(a/b), but ceil(a/b), and using the definitions and plots from Wikipedia:
With these plots of the floor and ceil functions, you can see the relationship.
You can see that floor(x) <= ceil(x). We need floor(x + s) = ceil(x). So we need to find s. If we take 1/2 <= s < 1 it will be just right (try some numbers and you will see it does, I find it hard myself to prove this). And 1/2 <= (b-1) / b < 1, so
ceil(a/b) = floor(a/b + s)
= floor(a/b + (b-1)/b)
= floor( (a+b-1)/b) )
This is not a real proof, but I hope you're satisfied with it. If someone can explain it better I would appreciate it too. Maybe ask it on MathOverflow.
157/32 is int/int, which results in an int.
Try using the double literal - 157/32d, which is int/double, which results in a double.
157/32 is an integer division because all numerical literals are integers unless otherwise specified with a suffix (d for double l for long)
the division is rounded down (to 4) before it is converted to a double (4.0) which is then rounded up (to 4.0)
if you use a variables you can avoid that
double a1=157;
double a2=32;
int total = (int) Math.ceil(a1/a2);
int total = (int) Math.ceil((double)157/32);
Nobody has mentioned the most intuitive:
int x = (int) Math.round(Math.ceil((double) 157 / 32));
This solution fixes the double division imprecision.
In Java adding a .0 will make it a double...
int total = (int) Math.ceil(157.0 / 32.0);
When dividing two integers, e.g.,
int c = (int) a / (int) b;
the result is an int, the value of which is a divided by b, rounded toward zero. Because the result is already rounded, ceil() doesn't do anything. Note that this rounding is not the same as floor(), which rounds towards negative infinity. So, 3/2 equals 1 (and floor(1.5) equals 1.0, but (-3)/2 equals -1 (but floor(-1.5) equals -2.0).
This is significant because if a/b were always the same as floor(a / (double) b), then you could just implement ceil() of a/b as -( (-a) / b).
The suggestion of getting ceil(a/b) from
int n = (a + b - 1) / b;, which is equivalent to a / b + (b - 1) / b, or (a - 1) / b + 1
works because ceil(a/b) is always one greater than floor(a/b), except when a/b is a whole number. So, you want to bump it to (or past) the next whole number, unless a/b is a whole number. Adding 1 - 1 / b will do this. For whole numbers, it won't quite push them up to the next whole number. For everything else, it will.
Yikes. Hopefully that makes sense. I'm sure there's a more mathematically elegant way to explain it.
Also to convert a number from integer to real number you can add a dot:
int total = (int) Math.ceil(157/32.);
And the result of (157/32.) will be real too. ;)
int total = (int) Math.ceil( (double)157/ (double) 32);
Check the solution below for your question:
int total = (int) Math.ceil(157/32);
Here you should multiply Numerator with 1.0, then it will give your answer.
int total = (int) Math.ceil(157*1.0/32);
Use double to cast like
Math.ceil((double)value) or like
Math.ceil((double)value1/(double)value2);
Java provides only floor division / by default. But we can write ceiling in terms of floor. Let's see:
Any integer y can be written with the form y == q*k+r. According to the definition of floor division (here floor) which rounds off r,
floor(q*k+r, k) == q , where 0 ≤ r ≤ k-1
and of ceiling division (here ceil) which rounds up r₁,
ceil(q*k+r₁, k) == q+1 , where 1 ≤ r₁ ≤ k
where we can substitute r+1 for r₁:
ceil(q*k+r+1, k) == q+1 , where 0 ≤ r ≤ k-1
Then we substitute the first equation into the third for q getting
ceil(q*k+r+1, k) == floor(q*k+r, k) + 1 , where 0 ≤ r ≤ k-1
Finally, given any integer y where y = q*k+r+1 for some q,k,r, we have
ceil(y, k) == floor(y-1, k) + 1
And we are done. Hope this helps.
There are two methods by which you can round up your double value.
Math.ceil
Math.floor
If you want your answer 4.90625 as 4 then you should use Math.floor and if you want your answer 4.90625 as 5 then you can use Math.ceil
You can refer following code for that.
public class TestClass {
public static void main(String[] args) {
int floorValue = (int) Math.floor((double)157 / 32);
int ceilValue = (int) Math.ceil((double)157 / 32);
System.out.println("Floor: "+floorValue);
System.out.println("Ceil: "+ceilValue);
}
}
I know this is an old question but in my opinion, we have a better approach which is using BigDecimal to avoid precision loss. By the way, using this solution we have the possibility to use several rounding and scale strategies.
final var dividend = BigDecimal.valueOf(157);
final var divisor = BigDecimal.valueOf(32);
final var result = dividend.divide(divisor, RoundingMode.CEILING).intValue();
int total = (157-1)/32 + 1
or more general
(a-1)/b +1
I have the following code :
Double x = 17.0;
Double y = 0.1;
double remainder = x.doubleValue() % y.doubleValue();
When I run this I get remainder = 0.09999999999999906
Any idea why??
I basically need to check that x is fully divisible by y. Can you suggest alternative ways to do that in java.
Thanks
Because of how floating-point numbers are represented.
If you want exact values, use BigDecimal:
BigDecimal remainder = BigDecimal.valueOf(x).remainder(BigDecimal.valueOf(y));
Another way to to that is to multiple each value by 10 (or 100, 1000), cast to int, and then use %.
You need to compare your result which allows for rounding error.
if (remainder < ERROR || remainder > 0.1 - ERROR)
Also, don't use Double when you mean to use double
Expecting precise results from double arithmetic is problematic on computers. The basic culprit is that us humans use base 10 mostly, whereas computers normally store numbers in base 2. There are conversion problems between the two.
This code will do what you want:
public static void main(String[] args) {
BigDecimal x = BigDecimal.valueOf(17.0);
BigDecimal y = BigDecimal.valueOf(0.1);
BigDecimal remainder = x.remainder(y);
System.out.println("remainder = " + remainder);
final boolean divisible = remainder.equals(BigDecimal.valueOf(0.0));
System.out.println("divisible = " + divisible);
}