What is wrong with arithmetic operation - java

I know perhaps is stupid question but I don 't understand what is wrong in the following operation:
value = 8.14
double netvalue = value / (1 + 23 / 100);
and the result is:
netvalue = 8.14

Division has precedence over addition, so
1 + 23 / 100 is evaluated as 1 + (23/100) which is 1 + 0 (23/100 is 0 since it is int division, so the result is an int), so you are dividing value by 1.
You can change 23 to 23.0 to achieve floating point division :
double netvalue = value / (1 + 23.0 / 100);
Or you can simply divide by 1.23 :
double netvalue = value / 1.23;

Let understand this
double netvalue = value / (1 + 23 / 100);
the first thing evaluated is 23/100 gives 0
and 1+ 0 = 1
and finally double netvalue = 8.14/1; gives 8.14

Related

Java on double: How to properly implement 'd' or 'D if there are many numbers or an expression to calculate?

It's said that we should put 'd' or 'D' after the number when you're creating a double variable. But what if I'm calculating many numbers.
double div = (6 % 4) / 10; // result 0.2
System.out.println("answer: " + div); // output: 0.0
Obviously, I will get an unexpected answer which is supposed to be 0.2 NOT 0.0... Now if I put 'd' or 'D' after the numbers, I will get a proper answer.
double div = (6d % 4d) / 10d; // result 0.2
System.out.println("answer: " + div); // output: 0.2
Should I put 'd' on all numbers in one expression when using double variable? or putting 'd' in one number is enough?
double div = (6 % 4) / 10d; //0.2
Just use dot with numbers or one of them
Result = (6 % 4) / 10.0;
Resoun: dividing int / int = int , otherwise int / double = double

Compute average of two double?

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)

The precendence of operators in Java is not applied

I have this piece of code and according to this page here
The below output should by right give me, 98.24 but this is giving me 68.8, what is that I am missing here?
public class Qn1
{
public static void main(String[] args)
{
double cel = 36.8;
double fah = ((9 / 5 )* cel) + 32;
System.out.println(cel + "deg C =" + fah +" deg F");
}
}
Use 9.0 / 5 instead of 9 / 5 in bracket.
9 / 5 is integer division and its value is 1. And hence the result. You just need to make one of the numerator or denominator a double / float value to enforce floating-point division.
((9 / 5 ) * cel) + 32 = (1 * 36.8) + 32 = 68.8
And what you need is: -
((9.0 / 5 ) * cel) + 32 = (1.8 * 36.8) + 32 = 66.24 + 32 = 98.24
double fah = ((9.0 / 5 )* cel) + 32;
The problem is you are not using double but int. Use
double fah = ((9d / 5d) * cel) + 32d;
Use at least one double operand:
double fah = 9.0 / 5 * cel + 32;
double fah = 9 / 5.0 * cel + 32;
double fah = 9.0 / 5.0 * cel + 32;
These three ways are valid and note that parenthesis are unnecessary.
9 is integer, so is 5 : so 9/5 is using integer division, meaning it results into 1 (integer) and not 1.8 (float)
1*36.8 +32 = 68.8
9 / 5 in integer arithmetic is 1

How to generate random numbers which will provide proper results on division

How to generate random numbers which will provide proper results on division (i.e the results should round to exactly 1 or 2 places after the decimal point).
(e.g a whole number by a decimal number providing decimal results - I have given a set of sample inputs below)
2827 by 2.5 = 1130.8
1747 by 0.8 = 2183.75
425 by 0.4 = 1062.5
935 by 0.8 = 1168.75
res = input * random.nextInt (100) / 100.0;
Explanation:
You take a whole number n, and multiply it with something. If this something is a number like 34.56, we call the part before the decimal digit w (whole part) and the part behind .xy.
If you multiply this with n, you end with (n*w)+(n*(x/10))+n*(y/100). There will never be an fractional part 3 ciphers behind the dot - do you agree?
We can combine x and y to a single part, and say (n*w) + (n*(xy/100)), and xy is just the name for something from 0 to 100.
Since the part before the decimal dot can be arbitrary large, you can calculate it seperately, if you need something else than 0. But you have to define a range somehow. If you take an random Integer R for that part:
res = input * R * random.nextInt (100) / 100.0;
Do you need the divisor explicityl?
div = 100.0 / (R * random.nextInt (100));
Scala is always handy, when testing code fragmenst:
val r = util.Random
r: util.Random.type = scala.util.Random$#ce2f12
scala> def res (input: Int) = input * r.nextInt (100) / 100.0;
res: (input: Int)Double
scala> (1 to 20).map (res)
res338: scala.collection.immutable.IndexedSeq[Double] =
Vector(0.48, 1.58, 0.48, 2.8, 0.15, 1.98, 5.67, 3.36, 6.93, 6.0, 9.02, 0.48, 7.41, 6.44, 9.6, 1.92, 16.66, 5.94, 7.98, 18.4)
It is worth noting that all integers can be divided by 0.4, 0.8 or 2.5 and be represented to two decimal places. This is because it is the same as multiplying by 2.5, 1.25, and 0.4
However, if you have a divisor for which this is not true, you can do this in a loop.
double divisor = 2.4;
double factor = 100/divisor;
Random rand = new Random();
int maxValue = 1000;
double ERROR = 1e-14*maxValue;
for(int i=0;i<100;i++) {
long randNum;
do {
randNum = rand.nextInt(maxValue+1);
if (Math.abs(randNum * factor - (long) (randNum * factor)) > ERROR)
System.out.println("reject "+randNum + " => "+randNum/divisor);
} while(Math.abs(randNum * factor - (long) (randNum * factor)) > ERROR);
System.out.println(randNum + " => "+randNum/divisor);
prints
729 => 303.75
285 => 118.75
84 => 35.0
123 => 51.25
999 => 416.25
75 => 31.25
reject 727 => 302.9166666666667
reject 842 => 350.83333333333337
504 => 210.0
reject 368 => 153.33333333333334
441 => 183.75
579 => 241.25
165 => 68.75
This will generate random numbers until you have a number which is a multiple of 0.01.
If you want the result to 'round' to 2 decimal places (it's not really rounding, it's just a finite decimal representation with two decimal points), then just generate the divisor, and have the dividend always be 100, e.g.:
106250 / 100 = 1062.5
116875 / 100 = 1168.75
If you want more interesting dividends then divide the divisor and dividend. e.g. the first one could be any one of:
(/1): 106250 / 100 = 1062.5
(/2): 53125 / 50 = 1062.5
(/10): 10625 / 10 = 1062.5
(/4): 26562.5 / 25 = 1062.5
(/125): 850 / 0.8 = 1062.5
For me the dividend and divisor are both random numbers. I have to produce an answer which doesn't require rounding decimals beyond 2 decimal places.
If that is the case, the answer might be "there is no such number". Here's a little Java program I wrote to test this hypothesis:
import java.text.DecimalFormat;
public class Test {
public static void main(String[] args) {
double num = Math.PI;
DecimalFormat format = new DecimalFormat(
"####################################0." +
"00##############################");
while (true) {
for (int i = 1; i < Integer.MAX_VALUE; i++) {
double tmp = (i / num) * 100;
if (tmp == (long) tmp) {
System.err.println("Solution - " + i + " - " +
format.format(tmp) + " - " + format.format(num));
break;
}
}
pi = Math.nextAfter(num, 1);
}
System.err.println("No solution for " + format.format(num));
}
}
I ran this for 10 minutes (starting at PI), and didn't find any values of num that had no solution i. But I did observe that solutions can be very sparse. For instance:
Gotcha! - 179453441 - 5712180438.00 - 3.1415926535897714
It took 179 million attempts to find the solution for that divisor.

How to round integer in java

I want to round the number 1732 to the nearest ten, hundred and thousand. I tried with Math round functions, but it was written only for float and double. How to do this for Integer? Is there any function in java?
What rounding mechanism do you want to use? Here's a primitive approach, for positive numbers:
int roundedNumber = (number + 500) / 1000 * 1000;
This will bring something like 1499 to 1000 and 1500 to 2000.
If you could have negative numbers:
int offset = (number >= 0) ? 500 : -500;
int roundedNumber = (number + offset) / 1000 * 1000;
(int)(Math.round( 1732 / 10.0) * 10)
Math.round(double) takes the double and then rounds up as an nearest integer. So, 1732 will become 173.2 (input parameter) on processing by Math.round(1732 / 10.0). So the method rounds it like 173.0. Then multiplying it with 10 (Math.round( 1732 / 10.0) * 10) gives the rounded down answer, which is 173.0 will then be casted to int.
Use Precision (Apache Commons Math 3.1.1)
Precision.round(double, scale); // return double
Precision.round(float, scale); // return float
Use MathUtils (Apache Commons Math) - Older versions
MathUtils.round(double, scale); // return double
MathUtils.round(float, scale); // return float
scale - The number of digits to the right of the decimal point. (+/-)
Discarded because method round(float,
scale) be used.
Math.round(MathUtils.round(1732, -1)); // nearest ten, 1730
Math.round(MathUtils.round(1732, -2)); // nearest hundred, 1700
Math.round(MathUtils.round(1732, -3)); // nearest thousand, 2000
Better solution
int i = 1732;
MathUtils.round((double) i, -1); // nearest ten, 1730.0
MathUtils.round((double) i, -2); // nearest hundred, 1700.0
MathUtils.round((double) i, -3); // nearest thousand, 2000.0
You could try:
int y = 1732;
int x = y - y % 10;
The result will be 1730.
Edit: This doesn't answer the question. It simply removes part of the number but doesn't "round to the nearest".
At nearest ten:
int i = 1986;
int result;
result = i%10 > 5 ? ((i/10)*10)+10 : (i/10)*10;
(Add zero's at will for hundred and thousand).
why not just check the unit digit...
1. if it is less than or equal to 5, add 0 at the unit position and leave the number as it is.
2. if it is more than 5, increment the tens digit, add 0 at the unit position.
ex: 1736 (since 6 >=5) the rounded number will be 1740.
now for 1432 (since 2 <5 ) the rounded number will be 1430....
I hope this will work... if not than let me know about those cases...
Happy Programming,
very simple. try this
int y = 173256457;int x = (y/10)*10;
Now in this you can replace 10 by 100,1000 and so on....
Its very easy..
int x = 1234;
int y = x - x % 10; //It will give 1230
int y = x - x % 100; //It will give 1200
int y = x - x % 1000; //It will give 1000
The above logic will just convert the last digits to 0. If you want actual round of//
For eg. 1278 this should round off to 1280 because last digit 8 > 5 for this i wrote a function check it out.
private double returnAfterRoundDigitNum(double paramNumber, int noOfDigit)
{
double tempSubtractNum = paramNumber%(10*noOfDigit);
double tempResultNum = (paramNumber - tempSubtractNum);
if(tempSubtractNum >= (5*noOfDigit))
{
tempResultNum = tempResultNum + (10*noOfDigit);
}
return tempResultNum;
}
Here pass 2 parameters one is the number and the other is position till which you have to round off.
Regards,
Abhinav
I usually do it this way:
int num = 1732;
int roundedNum = Math.round((num + 9)/10 * 10);
This will give you 1740 as the result.
Hope this will help.
int val2 = 1732;
val2 = (int)(Math.rint((double) i / 10) * 10);
The output is:1730
Have you looked at the implementation of Mathutils.round() ? It's all based on BigDecimal and string conversions. Hard to imagine many approaches that are less efficient.
Without using any math utils, rounding could be achieved to any unit as below:
double roundValue (double input, double toNearest){
//toNearest is any rounding base like 10, 100 or 1000.
double modValue = input % toNearest;
System.out.println(modValue);
if(modValue == 0d){
roundedValue = input;
}
else
{
roundedValue = ((input - modValue) + toNearest);
}
System.out.println(roundedValue);
return roundedValue;
}

Categories