This question already has answers here:
The accuracy of a double in general programming and Java
(2 answers)
Division of integers in Java [duplicate]
(7 answers)
Closed 6 years ago.
I have the following two calculation using Math.round(...):
double x = 0.57145732;
x = x * 100;
x = Math.round(x * 10);
x = x / 10;
If I now print the value of x it will show me: 57.1.
double x = 0.57145732;
x = (Math.round((x * 100) * 10)) / 10;
// x = (Math.round(x * 1000)) / 10; //Also gives me 57.0.
If I now print the value of x it will show me: 57.0.
Why is there this difference in the outcome?
The Math.round() method returns an integer (of type long - as pointed out by Ole V.V). It's usually thought to return a float or double which gives rise to confusions as these.
In the second calculation,
Math.round((x * 100) * 10)
returns 571. Now, this value and 10 both are integers (571 is long, 10 is int). So when the calculation takes the form
x = 571 / 10
where x is double, 571/10 returns 57 instead of 57.1 since it is int. Then, 57 is converted to double and it becomes 57.0
If you do
x = (double)Math.round((x * 100) * 10) / 10.0;
its value becomes 57.1.
Edit: There are two versions of the Math.round() function. The one you used accepts a double (since x is double) and returns long. In your case, implicit type casting spares you the trouble of considering the precise little details.
The reason of the difference is that in the second formula you're making a division of two integer. in order to have the same result you have to add a cast to double:
double x = 0.57145732;
x = (double)(Math.round((x * 100) * 10)) / 10;
The difference is between
x = Math.round(571.45732) / 10;
and
x = Math.round(571.45732);
x = x / 10;
Since round(double) returns a long, in the first case you divide a long by an int, giving the long 57. Converting back to double leads to 57.0. The second case is equivalent to
x = ((double)Math.round(571.45732)) / 10;
where a double is divided by an int, resulting in 57.1.
This because Math.round() returns an int. If you do this step-by-step (as in the first example), you assign the result of Math.round() to a float value. The following calculation uses then a float division.
In the second example, you let the JVM decide which types to use (and it uses an integer division as the intermediate step). This is why the precision gets lost.
Related
This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 3 years ago.
I was coding today, when I occurred this problem.
System.out.println(block.chance); // -> 10
float chanceFloat = block.chance / 100;
System.out.println(chanceFloat); // -> 0.0
I'm not sure what is the problem.
You are not stupid, you just are not aware of the language rules.
block.chance seems to be an integer, and the result of a division of two integers is an integer, even if it is assigned to a float cariable afterwards (then it is too late).
Your solution would be to use one of
float chanceFloat = block.chance / 100.0;
float chanceFloat = block.chance / 100.0f;
float chanceFloat = block.chance / 100.f;
float chanceFloat = block.chance / 100f;
float chanceFloat = (float)block.chance / 100;
If block.chance is an integer, then block.chance/100 will be performed as integer division (i.e., the result is truncated), and then cast to a float.
If block.chance is positive and less than 100, this will always be 0.
The simplest fix is to ensure that the divisions requires floating point numbers by changing the type of at least one side of the division. The common idiom would be
float result = block.chance / 100.0;
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.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I was going through a programming class and was asked this tricky question which was left unanswered till the end of the class.
Question:
How can I multiply any input(Float,int etc) by 7,
without using the * operator
in TWO steps.
If anyone can give me the answer for this question with the explanation , that would be very helpful.
With TWO STEPS I mean suppose you are running a loop (i=0;i<7;i++) in
that case number of steps will be >2, also TYPE CONVERSION,
DIVISION,ADDITION etc ( Counts for steps ).
Assuming float x or double x is defined in the scope. Then I see the following possibilities to multiply it by 7 without using the * operator:
In C++, you can use the standard functors (first step: create functor, second step: call functor):
x = std::multiplies<float>()(x, 7.0f); // if x is a float
x = std::multiplies<double>()(x, 7.0); // if x is a double
Or only use division (Since the compiler already evaluates 1.0 / 7.0, this is only one step):
x = x / (1.0f / 7.0f); // if x is a float
x = x / (1.0 / 7.0); // if x is a double
Or use the *= operator (technically, it's not the * operator, but it's only one single step):
x *= 7.0f; // if x is a float
x *= 7.0; // if x is a double
Or use addition in the logarithmic scale (this is not to be taken very serious, as well as this requires more than two "steps"):
x = exp(log(x) + log(7.0));
Another option is to use an assembly instruction, but I don't want to write that now, since it's overly complicated.
If x is an integer, bit shifting is another option, but not recommended:
x = (x << 3) - x; // (x * 8) - x
You could simply use division by a seventh:
x / (1.0 / 7)
Whether this counts as "two steps" is entirely up to your definition.
add it
//initialise s as the number to be multiplied
sum=0
for(i=0;i<7;i++)
sum+=s
In C, the following hack should work for floats stored in IEEE single precision floating point format:
#include <stdint.h>
float mul7 (float x) {
union {
float f;
uint32_t i;
} u;
u.f = x;
u.i += (3 << 23); /* increment exponent by 3 <=> multiply by 8 */
return u.f - x; /* 8*x - x == 7*x */
}
That's two steps (one integer addition, one float subtraction), sort of, depending on what you count as a step. Given that C++ is more or less backwards-compatible with C, I believe a similar trick should be possible there too.
Note, however, that this hack generally won't give correct results for subnormal, infinite or NaN inputs, nor for inputs so large in magnitude that multiplying them by 8 would overflow.
Adjusting the code to use doubles instead of float is left as an exercise for the reader. (Hint: the magic number is 52.)
You may also do the following for integers:
( x<< 3) - x
// String num = "10";
// int num = 10;
float num = 10;
BigDecimal bigD = new BigDecimal(num);
BigDecimal seven = new BigDecimal(7);
System.out.println(seven.multiply(bigD));
You could use the BigDecimal & its multiply method. Works for pretty much everything.
Define "two steps"...
float result = 0.0f;
float input = 3.14f;
int times = 7;
// steps
while (times--)
result += input;
Edit: dividing by (1 / 7) won't work with int type. Also in some languages for it to work with float type, you'd have to mark them as floats:
result = input / (1.0f / 7.0f);
Add 7 by x times.
for(int i=0; i<10; i++)
result = result+7;
When I do something like this
int test = 5 + 3 * (4 - 1) / 2;
I get 9. I suspected this was because int rounds down. However, when I do this
float test = 5 + 3 * (4 - 1) / 2;
I also get 9. However, when I do this
float test1 = 5;
float test2 = 4.5;
float test = test1 + test2;
Test finally outputs 9.5. Could someone explain the logic behind this? Why don't I get 9.5 in the second example? Thanks.
In your second example, although you are assigning the result to a variable of type float, the calculation itself is still performed exactly the same way as the first example. Java does not look at the destination variable type to determine how to calculate the right hand side. In particular, the subexpression 3 * (4 - 1) / 2 results in 4.
To fix this, you can use floating point literals instead of all integers:
float test = 5 + 3 * (4 - 1) / 2.0f;
Using 2.0f triggers floating point calculations for the arithmetic expression.
Although you represent the result of 5 + 3 * (4 - 1) / 2 in a float, the actual evaluation is done with the precision of an integer, meaning that the division of 9 / 2 returns 4 rather than the 4.5 you would receive if they were evaluated as floats.
Expressions have their own type. So start with:
5 + 3 * (4 - 1) / 2
Each value has its own type. This type happens to be int, so this is the same as:
((int)5) + ((int)3) * (((int)4) - ((int)1)) / ((int)2)
Making it clearer that we're dealing with ints. Only after this is evaluated as 9 does it get assigned to a float.
The short answer is that integer types operate on modular arithmetic, with modulus 1, and discard the remainder.
Since you cast test as an integer, modular arithmetic is employed with modulus 1 (e.g. 9.5 mod 1),
int test = 5 + 3 * (4 - 1) / 2;
With a 32-or-64 bit float this would give 9.5; however, because you have cast test as an int, the remainder is discarded, and the value referenced by test is 9.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Java Integer Division, How do you produce a double?
double wang = 3 / 2;
Log.v("TEST", "Wang: " + Double.toString(wang));
Logcat output...
07-04 09:01:03.908: VERBOSE/TEST(28432): Wang: 1.0
I'm sure there's an obvious answer to this and probably I'm just tired from coding all night but this has me stumped.
In many languages, Java being one of them, the way you write a number in an expression decides what type it gets. In Java, a few of the common number types behave like this1:
// In these cases the specs are obviously redundant, since all values will be
// cast correctly anyway, but it was the easiest way to show how to get to the
// different data types :P
int i = 1;
long l = 1L;
float f = 1.0f; // I believe the f and d for float and double are optional, but
double d = 1.0d; // I wouldn't bet on what the default is if they're omitted...
Thus, when you declare 3 / 2, you're really saying (the integer 3) / (the integer 2). Java performs the division, and finds the result to be 1 (i.e. the integer 1...) since that's the result of dividing 3 and 2 as integers. Finally, the integer 1 is cast to the double 1.0d which is stored in your variable.
To work around this, you should (as many others have suggested) instead calculate the quotient of
(the double 3) / (the double 2)
or, in Java syntax,
double wang = 3.0 / 2.0;
1 Source: The Java Tutorial from Oracle
Integer division of 3 by 2 is equal to 1 with residue of 1. Casting to double gives 1.0
3 and 2 are integer constants and therefore 3 / 2 is an integer division which results in 1 which is then cast into a double. You want 3.0 / 2.0
Try: double wang = 3.0 / 2.0;
That's the expected behaviour. "3" and "2" are both int values, and when you perform 3 / 2 the result will also be an int value which gets rounded down to 1. if you cast both to double before you perform the division then you'll get the result that you expect:
double wang = (double)3 / (double)2;