Casting from Java primitive int to double - java

If I call
methodName(5, 1/2);
and it has the signature
public static int methodName(int x, double y){
}
does the methodName receive y with a value of 0 or 0.5?

int y = 1/2;
At this point, y is 0. If you try to cast it to a double afterwards it will be 0.0. It doesn't remember how it got its value, just what its value is.
EDIT: I think the compiler will actually replace 1/2 with 0 at compile time. Making the code literally identical to int y = 0

int y = 1/2;
In this code, y will be 0;
If you want to get it as 0.5
Have a try with the following code:
double y = 1.0 * 1 /2; //y is 0.5

It will evaluate to 0.
There's not a whole lot you can do with the above code.
There should be no specific reason to store y as an int.
Try this instead:
double y = 1/2.0;

int y = 1/2
Since you're using 1 (int) and 2 (int) to make the division, it's an integer division, thus y = 0 (and remainder (%) is 1).

I think you are confused with parameters (the parenthesis). In java every method has a set of parameters (they might not hold values ex: exampleMethod()).
A parameter is a variable that is passed into the method, so when in your code you call:
methodName() initialize it with methodName(x,y);
the x and y inside the method are just pointers for the values you pass through the parameters. I would suggest that you name your variables differently to avoid this confusion. For example:
int x;
int y;
methodName(int argX, double argY)
{
}
Also to answer your question, an int cuts off its stored value at the decimal point, so 5.9 would round to 5 rather than 6, so if you needed a floating point variable for y, either declare it as a float or a double, either will work, but most methods in the java library are written to take doubles as parameters rather than floats

Related

Casting to Integer in Java when using type double

I have this simple code and I need to understand why the right side of the equation has been casted to Integer before getting the result in type double.
The answer here is 1.0 so I don't understand why it's not 1.5.
int x = 2;
double y = 1 + 1/x;
System.out.println(y);
simply update your code as following since you are dealing with doubles.
int x = 2;
double y = 1 + 1.0/x;
System.out.println(y);
Notice: double y = 1 + 1/x;
Modify: double y = 1 + 1.0/x;
You'll get 1.5
here x is an int and 1 is also an int so calculation is done in int and so you are getting the answer as 1.0. To get as 1.5 you have to typecast 1 to double as 1.0. Then you will get as 1.5.
I think what you meant was: why the value of 'x' on the right-hand side has not been 'promoted' to a double?
First, change the second line to :
double y = 1 + (double) 1 / x;
//or
double y = 1 + 1.0 / x;
Details:
Simply for most computers to perform arithmetic operations operands must be of identical data types.
The cast operator (double) performs explicit conversion of its operand to double, then the variable ' x ' will be implicitly converted to a double which is called promotion.
also in the second line 1.0 is already a floating-point constant so you can guess that this is the same as before, that is a promotion to the variable 'x' will occur.
What you have done in your code is called Integer Division meaning that the fractional part of the division will be lost (truncated). Note that the fractional part is lost before it is assigned to the variable y.
You may have some intuition now on why we didn't write the code like that:
double y = 1.0 + 1 / x;
clearly, (1 / x) is still integer division ...hope that helps!
Like user markspace noted in a comment, the integer division happens because / has a higher order of precedence than =, which means that the division takes place first in the statement.
double y = 1 + (1/2); // Both 1 and 2 are integers at the time of operation.
// The above equation is the same as
double y = 1 + 0; // 1/2 equals 0 because integer division just keeps the integer value
// and gets rid of the value's decimal part.
Similar to what the other answers have shown, you can do something like one of the following:
double y = 1 + 1.0/x;
// Or
double y = 1 + 1/(double)x;
Just for simplicity, when I use integer literals when assigning double values, I just make all the integers have the .0 part. For example, instead of 1, I would always put 1.0. That way, you will never accidentally get unexpected results because of unwanted integer division.
Check out this page in the Java doc for the order of precedence for operators in Java.

How do I figure out how many times I have to add a short to get the value of another short?

How does one figure out how many times one has to add a short to get the value of another short?
I know, I know, it's a weirdly phrased question. But in more specifics without all the primitive types of Java...
Basically, I have a short x, which we'll use the placeholder 7 for. I also have a short y, which I'll say is the number 5. And then, I have a short z, which I'll say is 236.
Now, what I want to do, is get an integer that counts how many times I have to add the number y (5) to the number x (7) to get to the maximum value of z (236).
Obviously, I could do that somewhat with a pencil and paper right now, but what I need is something that I can input the 3 values and it will give me the integer as the output - the number of times I have to add the value y to the number x to get to the maximum value of z.
If you still don't understand what I'm doing, then a more visual example is:
(Y * someint) + X = Z How would I get to someint?
int result = (z - x) / y;
The result is int even if division has a remainder which is ignored in this case.
As others have stated this is simple division. But if you're looking for other completely unnecessary ways to do this, heres a loop way...
public static int getNumOfAdds(short x, short y, short target){
int i;
for(i = 0; y*i + x < target; i++){}
return i;
}
val = (Z-X)/Y;
rem_val = (Z-X)%Y;
if (rem_val != 0)
val++;
This should do it.
Recursively?
Try something like
Func(short x , short y, short z, int c)
if ( x >= z )
return c
else
return Func(x+y,y,z,c)
and your first call would be Func(x,y,z,0)

Math.round and Math.ceil not working

I'm trying to round the users input but I can seem to get my double to round to an int. Basically, when I enter 4.4999 it wont round up to 5.
Any ideas?
Math.ceil() returns the ceiled value. It can't change the value of the variable it takes as argument, because Java passes arguments by value. So you need to do
hours = Math.ceil(hours);
The actual solution is to use double inside the ceil method.
Math.ceil(7 * 50 / 100) will return 3.0 even though the actual value resulting from 7*50/100 is 3.5. It is because since everything is int, the result of 350/100 itself will be 3.
If however, if you give Math.ceil(7 * 50 / 100D), the result would be 4.0.
So, the 4.999 in your question should be a double and not a result of an integer operation like 4999/1000.
Just make sure that whatever you give inside a the ceil is double and not an int.
Both function return the rounded (or ceiled) values, but don't change the variable passed as parameter.
Use eg. hours = Math.ceil(hours);.
Math.ciel returns a Double. Something like this should work (inside of your hours > 0 block):
cost += Math.ceil(hours) * hourlyRate;
You're not assigning the result of Math.ceil(hours) back to hours so it will never round.
int a = 15
int b = 2;
int x = (int) Math.ceil( a / b );
int y = (int) Math.ceil( (double) a / (double) b );
Results:
x: 7
y: 8

Java: Calc x in sin(x)

My question is about angle functions in programming languge Java. if i want to get sin of any double, i just use
double variable = Math.sin(x);
but what if sin(x) = 0.324 (or any other random number) and i want to calculate x? How can i do it? Are there any native function to this in java or i have to implement my own algorithm to return this value ?
getXForValue(0.324);
public double getXForValue(double val){
// how to calculate ?
return x;
}
Thanks.
What you are describing is known as the "arcsine" function. It's available in Java as Math.asin().
You may want to read the wiki on trigonometric functions.
Use the arcsin function
x = Math.asin(variable)
To calculate sine inverse in Java you can use
Math.asin(double a)
It returns the arc sine of a value; the returned angle is in the range -pi/2 through pi/2.. Check java docs for more explanation
You can use Math.asin(0.324); to get the value of x.
Please read the Math.asin() javadoc to be aware of what is returned by the function.
You have to use the inverse function or arcsine. It has the same relationship with sine as dividing has with multiplication.
5 * x = 10;
10 / 5 = x;
Math.sine(x) = 1;
Math.asine(1) = x;
you need to use the these Methods, Math.toDegrees and Math.asin, in the next order:
double x = 1.0; // in this example 1.0 corresp to sin(90)
double dX = Math.toDegrees(Math.asin(x));
System.out.println(dX);
Remember that the asin() function return a double RADIANS result.

Converting double to integer in Java

In Java, I want to convert a double to an integer, I know if you do this:
double x = 1.5;
int y = (int)x;
you get y=1. If you do this:
int y = (int)Math.round(x);
You'll likely get 2. However, I am wondering: since double representations of integers sometimes look like 1.9999999998 or something, is there a possibility that casting a double created via Math.round() will still result in a truncated down number, rather than the rounded number we are looking for (i.e.: 1 instead of 2 in the code as represented) ?
(and yes, I do mean it as such: Is there any value for x, where y will show a result that is a truncated rather than a rounded representation of x?)
If so: Is there a better way to make a double into a rounded int without running the risk of truncation?
Figured something: Math.round(x) returns a long, not a double. Hence: it is impossible for Math.round() to return a number looking like 3.9999998. Therefore, int(Math.round()) will never need to truncate anything and will always work.
is there a possibility that casting a double created via Math.round() will still result in a truncated down number
No, round() will always round your double to the correct value, and then, it will be cast to an long which will truncate any decimal places. But after rounding, there will not be any fractional parts remaining.
Here are the docs from Math.round(double):
Returns the closest long to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result, and casting the result to type long. In other words, the result is equal to the value of the expression:
(long)Math.floor(a + 0.5d)
For the datatype Double to int, you can use the following:
Double double = 5.00;
int integer = double.intValue();
Double perValue = 96.57;
int roundVal= (int) Math.round(perValue);
Solved my purpose.

Categories

Resources