Math.pow() returns [float]E[int] [duplicate] - java

This question already has answers here:
Java and decimals E numbers
(2 answers)
Closed 8 months ago.
I was working on some problem in codeforces just for practice and the implementation I came up with is based on using the Math.pow() method in Java:
import java.io.*;
import java.util.*;
public class TestClass {
public static void main(String[] args) {
MyScanner sc = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out));
long t = sc.nextLong();
//note that "MyScanner" is a pre-defined class for buffered input
//just to make it easier to call the methods
while (t-- > 0){
String m = sc.next();
long l = m.length(), n = Long.parseLong(m);
out.println(n - Math.pow(10, l-1));
}
out.close();
}
}
I/O example: the input can be too big, that's why I used the long datatype.
Input:
7
1
2
178
20
999999999
9000
987654321
Output:
0
1
78
10
899999999
8000
887654321
but instead I get this:
0.0
1.0
78.0
10.0
8.99999999E8
8000.0
8.87654321E8
as you can see, my solution seems to be correct, but the output was in different form.

The method you use has the following signature: static double pow(double a, double b). This means, the parameters will automatically be cast to double and it's return value is also a double.
There is no overload for a long return value so you will either have to cast the result manually to long with this: n - (long)Math.pow(10, l-1).
Edit: or use another solution like the BigInteger one, but be aware that BigInteger (and BigDecimal) only accepts int as exponent, not long and not BigInteger.

Math.pow won't guarantee 100% accuracy on large integer values beyond some threshold (see this question for details) because floats and doubles cannot accurately represent all integers supported by the long type. Therefore, I would recommend you to use a BigInteger, which also has a pow function and will give you correctly formatted results out of the box.

Related

Java Multiple Two numbers issue with negative numbers [duplicate]

This question already has answers here:
Why I am getting -2147483648 and -1's multiplication, negative i.e. -2147483648, instead it should be +2147483648 [duplicate]
(1 answer)
How does Java handle integer underflows and overflows and how would you check for it?
(12 answers)
How are integers internally represented at a bit level in Java?
(10 answers)
Why does the negative of Integer.MIN_VALUE give the same value? [duplicate]
(2 answers)
Closed 2 years ago.
I’m recently facing the below problem
public class Main {
public static void main(String[] args) throws Exception {
// Your code here!
int i = -2147483648;
int j = i * -1;
System.out.println("j="+j);
}
}
Result : -2147483648
Online IDE with code :
https://paiza.io/projects/e/17lF_6-GltIcyubZv3QoFg?theme=twilight
But how it’s works as per the logic I need to get 2147483648 is a result right?
Then how I got this negative number ?
It’s because of integer range (Integer.MIN_VALUE)?
how to fix this issue?
The maximum postive value an int can hold is 2147483647 beyond which the value goes to the other end (i.e. it starts from the negative end). You can understand it from the following demo:
public class Main {
public static void main(String[] args) {
int i = -2147483648;
int j = i * -1;
System.out.println("j=" + j);
System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.MAX_VALUE + 1);
System.out.println(Integer.MIN_VALUE);
// Some more examples for you to understand this concept better
System.out.println(Integer.MAX_VALUE + 2);
System.out.println(Integer.MAX_VALUE + 3);
}
}
Output:
j=-2147483648
2147483647
-2147483648
-2147483648
-2147483647
-2147483646
After -2147483648 is multipled with -1, it becomes 2147483648 but an int variable can not hold this much big positive value; so, it will start from the negative end (i.e. Integer.MIN_VALUE).
The number 2147483648 does not exists. The biggest value of an int is 2147483647, which is 1 smaller than your expected result. The multiplication causes an overflow, which 'rolls back' the number to the smallest negative value, and continues the calculation from there. (With other words: 2147483647+1=-2147483648 (smallest negative)) Since the result would only be 1 over the maximum value, there is no additional action required and the minimal int value is returned.
If you want to fix this issue, use 'long' instead of 'int' for your variables. You can also use more complex classes like BigDecimal, or write a custom multiplication function for byte arrays.
Note: no matter what numeric type you use, as long as the memory used for representing the number is finite you can run into similar issues. Although under normal circumstances it is unlikely, even for a 32-bit integer (int).

Order of operations with multiplication, subtraction, and division in Java?

Below is the code and I wanted to know why it gives an output of 2.0 instead of 0.0?
class Main {
public static void main(String[] args) {
double x = 5*4/2 - 5/2*4;
System.out.println(x);
}
}
Because 5/2 is 2 not 2.5. 5 and 2 is integer and / operator generates int.
Integer division truncates any decimal places. You are probably expecting 5/2*4 to equal 10, but it is actually resolving to 8.
This can be solved by writing your numbers like this:
double x = 5.0*4.0/2.0 - 5.0/2.0*4.0;
Simply storing the result in a double does not force the actual arithmetic to consider the values to be doubles.
You're working with integers. So 5/2*4 equals 8.

Java casting (cast operator expressions) [duplicate]

This question already has answers here:
Integer division: How do you produce a double?
(11 answers)
Closed 6 years ago.
The question require me to write a Java program to show the results of the following cast operator expressions:
(double) (23 / 14) + 7.65
My Code:
public class op {
public static void main(String [] args) {
int num = 23/14;
double r1 = (double) num;
double result = r1 + 7.65;
System.out.println("Results: "+ result);
}
}
I don't think I have done correctly, what are the problems of my code?
By the way, can someone tell me what are the differences between long, double, int, float? How do we know when to use these primitive data types? I read an explanation here: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
but is there any 'human-version' of the explanation?
Thank you for your help.
The problem is due to the used types.
Since you divide two integers (23 and 14), the result is considered and int as well. Therefor, 23/14 = 1.642857142857143, which is truncated to fit in an int result, more specifically, 1.
result is the sum of 1 (int) and 7.65 (double). Since one of them is a double, to other is converted to the "upper" type as well (double) and the operation becomes 1.0+7.65 = 8.65.
The result is correct, because you asked the result of (double) (23 / 14) + 7.65 which means the result of casting the result of the operations in brackets to double summed with 7.65. Which is 8.65 as previously explained.
If you want to use a division using doubles, consider:
double r1 = 1.0 * 23/14;
Lets see step-by-step:
int num = 23/14; // int division of 23/14 results in 1
So, here num = 1
When you cast num to double value of r1 is setted to 1.0.
double result = r1 + 7.65; //1.0 + 7.65 = 8.65
ok, int is short term for INTEGER which are natural numbers that we use normally but with no decimal places and if your number has some value in between roughly -2 billion to +2 billion. if your range exceeds that and you still want an integer then go for long data type.
floats are for decimal values like 3.147 with a range of +10*38 to -10*38 or so, but if your range exceeds this(practically this happens rarely) go for double.
coming to the code you put here , if you divide a int by another int (like 23/14) you get only get the integer part of the answer(only '1' in 23/14=1.642...) , next when you cast it to double you get 1.0 and next you are going to add that to 7.65 which will make the ultimate answer as 8.65 hope this answers your Q....
You could change this int num = 23/14
to double num = ((double) 23)/14
or double num = (23 * 1.0)/14

Why do I need to add an 'f' to value so my code outputs the right value? [duplicate]

This question already has answers here:
Why does the division of two integers return 0.0 in Java? [duplicate]
(6 answers)
Closed 9 years ago.
The following is my code that works ::
public class AvgSpeed{
public static void main(String[] args){
double kph, km, hours, seconds, minutes, time;
km = (1.6 * 24);
hours = 1;
minutes = 2/3f;
seconds = 35/3600f;
time = hours + minutes + seconds;
kph = km/time;
System.out.println(kph);
}
}
If I remove the f's for minutes and seconds, it keeps printing out 38.4, which is not right. It should be some number close to 22.906
I don't even know the reason why I need to add the f, I did it on a whim. I thought declaring the two variables as a double was enough?
Declaring the variables as doubles doesn't make 2 or 3 a double. The conversion to double only happens after 2/3 is computed in integer arithmetic. To fix this, do the calculation in double arithmetic:
minutes = 2.0/3;
// ^ double
seconds = 35.0/3600;
// ^ double
The trailing f you appended made 3f and 3600f float literals. That's close to what you want, but not as good as doubles.
In Java, 18.45 is a double data type which holds 64-bit. float data type can hold up to 32-bit only. Adding the extra f makes it a float (float literal).
See http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html for more detail
double minutes;
minutes = 2/3;
This code takes two integers, divides them, converts the result to a double and stores it in minutes. In that order. To get the result you want you need to convert to doubles before the division happens. You managed to do this by adding f (use d for double, btw). You could also do it with minutes = 2.0/3.0;

Java - PHP Number-Type Mix Up (9966006699)

I was doing some stuff with palindromes:
This number 9966006699 has been giving me problems. It's a product of 99979 and 99681
99979 * 99681 = 9966006699
I ran that in PHP
$i = 99979 * 99681;
echo $i;
var_dump($i);
Outputs
9966006699 float(9966006699)
So in PHP the product is obviously a float data type. But in Java it's different as seen below :
This
public static void main(String[] args) {
float f = 99979 * 99681;
System.out.println(f);
long o = 99979 * 99681;
System.out.println(o);
double d = 99979 * 99681;
System.out.println(d);
int i = 99979 * 99681;
System.out.println(i);
}
Outputs
1.37607206E9
1376072107
1.376072107E9
1376072107
Google's calculator gives the right thing
I'm lost, why is Java giving the wrong output? and Does it have anything to do with the E9 stuff behind the float and double types? Help. Thanks
The numbers 99979 and 99681 are both int's. The multiplication expression is therefore an int expression too. The maximum value of an int expression is 2147...... Your value 9966006699 is way above that. Hence you have fallen in the realms of the strange behaviour that you get from modulo-n arithmetic. (That is, you have fallen victim to the C-family languages' version of the Y2K problem.)
Try this :
long o = (long)99979 * 99681;
System.out.println(o);
It looks like integer overflow as 9 966 006 699 > Integer.MAX_INT = 2 147 483 647. As int times int have type int the result overflows. Then it is cast to int/float/long etc.
This should be correct (for non-int):
long value = (long)99979 * (long)99681
Alternativly you can use BigInteger class which:
May be slower the using int/long
Don't have this problem for any numbers (long just moves the problem from 2^31 - 1 to 2^63-1).
Integer.MAX_VALUE is equal to 2^31-1, which is smaller than the number you're dealing with, so you're essentially getting integer overflow issues. You can get around this by using a long, or the BigInteger class.
You can read about the numeric limits of primitive data types here:
http://download.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

Categories