Casting a double result from a divison into an int in Java - java

I want to use a method that requires an int. This int is determined by a division potentially solved as a double. I need to perform this as neat and short as possible and I am wondering if I can count that the method will take the double directly casted as int and if this means a single truncation with no roundings.
Do I have to necessarily use Math static methods?
Could this give errors for non int parameter entries to subList?
Could someone provide any guidance about this?
List<Integer> b = null;
List<Integer> c = null;
int size = a.size();
b.addAll(a.subList(0, size / 2)); // To hold the first half
c.addAll(a.subList(size / 2, size)); // To hold the second half [and excess]
Thank you in advance for your help.

it will take the double casted to integer and will not round it, just disregard everything after the "."
so if the division of 9.8/2 is 4.9 then you'll get 4 for doing
int x = 9.8/2;
you don't need to use the Math static methods for devision and you won't get errors for the code you gave
to conclude, you can just run your code and see if the result is as you want it.
b.addAll(a.subList(0, size / 2));
should run without problem

What's wrong with b.addAll(a.subList(0, (int)(size / 2)));?

Related

How can one scale an Int64 value without access to a larger type?

I refactored the code in this class to be in a form that is more friendly to my use cases; one issue that I noticed during testing is that I cannot convert this particular equation to use long inputs because assigning to the a and m variables overflow on the multiplication/subtraction steps. Everything is just peachy when using int inputs because they can be casted to a long to prevent overflow. Is there anything one can do to get the proper behavior when the inputs are long?*
public static Func<int, int> Scale(int inputX, int inputY, int outputX, int outputY) {
if (inputX > inputY) {
var z = inputX;
inputX = inputY;
inputY = z;
}
if (outputX > outputY) {
var z = outputX;
outputX = outputY;
outputY = z;
}
var a = (((((double)inputScaleX) * (outputScaleX - outputScaleY)) / ((long)inputScaleY - inputScaleX)) + outputScaleX);
var m = (((double)(outputScaleY - outputScaleX)) / ((long)inputScaleY - inputScaleX));
return (value) => ((int)((value * m) + a));
}
For example, if I replaced every instance of int in the function above with long then result will have an incorrect value in the following code:
Func<long, long> scaler = Scale(long.MinValue, long.MaxValue, -5, 5);
var result = scaler(long.MaxValue - 3);
The expected result is 4 but the actual result of -9223372036854775808 is not only wrong, it ends up being way outside the defined range of [-5, 5].
*Other than straight up using BigInt or implementing 64-bit multiplication and division in software; I am already implementing these operations as workaround and am looking for alternative solutions that I haven't yet come across.
If you have to do math and none of the buildin .NET Integer types is long/large enough, BigInt is the droid you are looking for.
As long as you do not run out of memory, it can take a number of arbitrary size. Do however note that the performance is very bad, as should be expected. After all, Arbtitrary size does not come without tradeoffs. And unlike any other Numeric type, it can grow big.
Looking at the source code, it seems to be little more then a List<uint> with a int for the sign. Unfortunately that designs makes it vulnerable to Fragmentation based OutOfMemory exceptions and related List<uint> growth issues. I was hoping it would use a Linked List internally, but no such luck.
Java has a equivalent type (I asume all higher languages do), but I have no data on it's workings.

Why is variable displaying 0?

This is my first time using StackOverflow so sorry if my question is nooby as I am learning Java. What I am trying to do now is pass a variable from one method into another method(same class) so I can show the value in a graph. My code is below:
Method 2
private void Average(){
System.out.println(openessAverage);
DefaultCategoryDataset bc = new DefaultCategoryDataset();
bc.setValue(openessAverage, "Percentage", "Openess"); //Show here
JFreeChart jchart = ChartFactory.createBarChart3D("Big 5 Graph", "ID","Percentage" , bc, PlotOrientation.VERTICAL,true,true,false ); //chart
CategoryPlot plot = jchart.getCategoryPlot();
ChartFrame chartFRM = new ChartFrame("Personality Insight", jchart,true);
chartFRM.setVisible(true);
chartFRM.setSize(800,600); //Sets JFrame size
}
When I run that code it gives me 0.0 in the console and graph is also 0. Any idea why? would really appreciate the help:)
the reason is pretty simple
dividing integers will return an integer too.
therefore
double c = a/b;
will be zero if b > a
solution: cast one of the operands to double
double c = (double)a/b
The probelm has to do with the fact that you are dividing a double by an integer. Any time you do that, basically Java truncates the result (removes the decimal). In your case, the size of the list is probably greater than what it's dividing, so it's rounding down to 0. To fix this, you can either cast opennes.size() to a double, or better, just cast that operation to a double.
Double num = (double) num1/num2;
Hope that helps

What is the priority of casting in java?

if I have a line of code that goes something like
int s = (double) t/2
Is it the same as
int s = (double) (t/2)
or
int s = ((double) t)/2
?
See this table on operator precedence to make things clearer. Simply put, a cast takes precedence over a division operation, so it would give the same output as
int s = ((double)t) / 2;
As knoight pointed out, this is not technically the same operation as it would be without the parentheses, since they have a priority as well. However, for the purposes of this example, it will offer the same result, and is for all intents and purposes equivalent.

Java / Android - equation for rounding up

I am building an android application. In my app, i need to be able to round up a double (42.42 for example) and also get how much i added to the original number in order to round it up. My current code isn't working, and its outputting 0.. Anyway to fix this?
My current code:
float rounded = FloatMath.ceil(val);
double getDecimal = (val - FloatMath.floor(val))*100;
int noDecimal = (int) ((int) 100-getDecimal);
float toadd = (noDecimal/100);
In my code the "rounded" variable is the simpel rounding, and "toadd" should be how much i added to it. For some reason toadd always comes back as 0. Any help?
You're dividing noDecimal by 100. Both are ints, and the result will always be an int. In this case, it's an int between 0 and 1, which will always be truncated to 0.
What's wrong with just getting the number modulo 1 (%1), then getting the ceiling of the original number?
For completeness, you could simply change the last line to preserve the rest of the logic:
float toadd = noDecimal/100.0;
This changes the divisor to a float, and an int divided by a float yields a float.
float toadd = (noDecimal/100);
This will give you 0, as you are dividing smaller integer by larger one..
Try to do like this: -
float toadd = (Float.valueOf(noDecimal)/100);
Also, you don't need to do typecast twice in the below code: -
int noDecimal = (int) ((int) 100-getDecimal);
Just, outer cast is enough: -
int noDecimal = (int) (100-getDecimal);
Edit: - Also, you might want to use BigDecimal for this kind of problems..
Maybe I'm missing something or not getting your intention right, but if you just want to know what you added, why don't just use the difference?
float rounded = FloatMath.ceil(val);
float toadd = rounded-val;
Edit: As mentioned in the comments, this might not always give the absolutely accurate result. But it's the general idea which can be used with BigDecimal, which offers a higher precision.

Java math function to convert positive int to negative and negative to positive?

Is there a Java function to convert a positive int to a negative one and a negative int to a positive one?
I'm looking for a reverse function to perform this conversion:
-5 -> 5
5 -> -5
What about x *= -1; ? Do you really want a library function for this?
x = -x;
This is probably the most trivial question I have ever seen anywhere.
... and why you would call this trivial function 'reverse()' is another mystery.
Just use the unary minus operator:
int x = 5;
...
x = -x; // Here's the mystery library function - the single character "-"
Java has two minus operators:
the familiar arithmetic version (eg 0 - x), and
the unary minus operation (used here), which negates the (single) operand
This compiles and works as expected.
Another method (2's complement):
public int reverse(int x){
x~=x;
x++;
return x;
}
It does a one's complement first (by complementing all the bits) and then adds 1 to x. This method does the job as well.
Note: This method is written in Java, and will be similar to a lot of other languages
No such function exists or is possible to write.
The problem is the edge case Integer.MIN_VALUE (-2,147,483,648 = 0x80000000) apply each of the three methods above and you get the same value out. This is due to the representation of integers and the maximum possible integer Integer.MAX_VALUE (-2,147,483,647 = 0x7fffffff) which is one less what -Integer.MIN_VALUE should be.
Yes, as was already noted by Jeffrey Bosboom (Sorry Jeffrey, I hadn't noticed your comment when I answered), there is such a function: Math.negateExact.
and
No, you probably shouldn't be using it. Not unless you need a method reference.
original *= -1;
Simple line of code, original is any int you want it to be.
Necromancing here.
Obviously, x *= -1; is far too simple.
Instead, we could use a trivial binary complement:
number = ~(number - 1) ;
Like this:
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
int iPositive = 15;
int iNegative = ( ~(iPositive - 1) ) ; // Use extra brackets when using as C preprocessor directive ! ! !...
System.out.println(iNegative);
iPositive = ~(iNegative - 1) ;
System.out.println(iPositive);
iNegative = 0;
iPositive = ~(iNegative - 1);
System.out.println(iPositive);
}
}
That way we can ensure that mediocre programmers don't understand what's going on ;)
The easiest thing to do is 0- the value
for instance if int i = 5;
0-i would give you -5
and if i was -6;
0- i would give you 6
You can use the minus operator or Math.abs. These work for all negative integers EXCEPT for Integer.MIN_VALUE!
If you do 0 - MIN_VALUE the answer is still MIN_VALUE.
For converting a negative number to positive. Simply use Math.abs() inbuilt function.
int n = -10;
n = Math.abs(n);
All the best!
In kotlin you can use unaryPlus and unaryMinus
input = input.unaryPlus()
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/unary-plus.html
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/unary-minus.html
You can use Math:
int x = Math.abs(-5);

Categories