What are the 22 possible values of x where x== -x (true)? - java

Recently this question asked in Java interview. Tried and searched the solution but can't find. kindly, comment the solution if anybody knows. It would be helpful.

Zeroes in the numeric basic types. Float and double have two zeroes each. That's nine values. Then there's MIN_VALUE for int and long. That's eleven.
So:
int x = 0;
int x = Integer.MIN_VALUE;
long x = 0;
long x = Long.MIN_VALUE;
byte x = 0;
short x = 0;
char x = 0;
double x = 0.0;
double x = -0.0;
float x = 0f;
float x = -0f;
Then each of those values wrapped as an object:
Integer x = 0;
Integer x = Integer.MIN_VALUE;
Long x = 0L;
Long x = Long.MIN_VALUE;
Byte x = 0;
Short x = 0;
Character x = 0;
Double x = 0.0;
Double x = -0.0;
Float x = 0f;
Float x = -0f;
That's 22 total.
(I wouldn't have called the objects more values. They're the same 11 values again but wrapped in objects. But if you're supposed to find 22 total, I think this must be it.)
Note that for smaller integral types, like short, performing -x would widen them to an int, so x==-x does not work for Short.MIN_VALUE.
x==-x evaluates as true for floating-point zeroes, because even though positive zero and negative zero are different values, they are regarded as equal to each other.

Related

Implementation of FitzHugh-Nagumo diffusion model diverging by first iteration

I'm trying to implement the model described in this paper, which simulates the equation proposed by Alan Turing of the FitzHugh-Nagumo model in 2D as a model for forming animal skin patterns — in other words: simulating two substances diffusing across a surface, how they interact with each other, and what patterns arise. This is the paper's result:
                                            
I've implemented it (my interpretation of at least) in Processing/Java, but it's not working like it should (values are diverging lots, even by the first iteration), so I'm wondering what's going wrong in my implementation (included at the end of the post).
These are the 3 relevant parts from the paper regarding implementation:
1. U & V
There are two substances, u and v (which can be thought of as an activator and inhibitor respectively)
2. Finite difference equations
A fairly simple pixel convolution is defined for each value (pixel) of u and v. Values for a given pixel on the next generation are calculated using both it and its neighbours' current-iteration values.
The value of u on the n+1 iteration for a given pixel (i,j) is defined as:
The value of v on the n+1 iteration for a given pixel (i,j) is defined as:
3. Constants they used
So the problem I'm getting is that the values of u and v are quickly diverging to infinity/NaN (I expect they should stay within 0...1 although the paper doesn't explicitly mention this). v seems to diverge first, taking u along with it, as can be seen here (for some constant index):
0.94296926 0.77225316 // u, v after random initialisation
0.91600573 -62633.082 // values after first iteration -- v has already diverged massively
63.525314 5.19890688E8 // second iteration -- even more divergence
-520088.38 -2.98866172E14 // ...and so on...
1.40978577E14 1.2764294E19
-Infinity -1.7436987E24
NaN NaN
NaN NaN
Code
//Parallel Simulation of Pattern formation in a reactiondiffusion system of Fitzhugh-Nagumo Using GPU CUDA
// Alfredo Gormantara and Pranowo1
static final float a = 2.8e-4;
static final float b = 5.0e-3;
static final float k = -0.005;
static final float tau = 0.1;
static final float delta_t = 1e-3;
float[][] u; // activator
float[][] v; // inhibitor
void setup() {
size(512, 512);
frameRate(5);
u = new float[height][width];
v = new float[height][width];
for (int i = 0; i < u.length; i++) {
for (int j = 0; j < u[0].length; j++) {
u[i][j] = random(1); // random of max of 1 ?
v[i][j] = random(1); // random of max 1?
}
}
loadPixels();
}
void draw() {
float[][] u_n_1 = new float[height][width]; // array holding the n+1 iteration values of u
float[][] v_n_1 = new float[height][width]; // array holding the n+1 iteration values of v
float denom = 2f / width; // 2/MESH_SIZE -- I think mesh_size is dimension of the grid
denom*=denom; // square for denominator
println(u[34][45], v[34][45]); // print vals of one location to see divergence
for (int y = 0; y < height; y++) {
int negative_y_i = y-1 < 0 ? height-1 : y-1; // wrap around grid
for (int x = 0; x < width; x++) {
final float u_n = u[y][x];
final float v_n = v[y][x];
int negative_x_i = x-1 < 0 ? width-1 : x-1; // wrap around grid
// calculate laplace (12)
float u_n_1_laplace = u[y][(x+1) % (width)] + u[y][negative_x_i] + u[(y+1) % (height)][x] + u[negative_y_i][x]; //n+1th iteration
u_n_1_laplace -= (4 * u_n);
u_n_1_laplace /= denom; // divide by (2/DIM)^2
u_n_1_laplace *= a;
// calculate n+1th iteration u value
u_n_1[y][x] = u_n + delta_t*( u_n_1_laplace + u_n -(u_n*u_n*u_n) - v_n + k );
// calculate laplace (14)
float v_n_1_laplace = v[y][(x+1)% (width)] + v[y][negative_x_i] + v[(y+1)% (height)][x] + v[negative_y_i][x]; //n+1th iteration
v_n_1_laplace -= (4 * u_n);
v_n_1_laplace /= denom; // denom is really small, so value goes huge
v_n_1_laplace *=b;
v_n_1[y][x] = v_n + (tau/delta_t)*( v_n_1_laplace + u_n - v_n);
pixels[y*width + x] = color((int) ((u_n_1[y][x]-v_n_1[y][x])*255));
}
}
u = u_n_1.clone(); // copy over new iteration values
v = v_n_1.clone(); // copy over new iteration values
updatePixels();
}

Force integer division on a double?

I have
x /= y;
Where x & y are both double
I would like x to be the integer part of x/y , how do I do this?
I have tried
x /= y;
x = x.intValue();
But am receiving a double cannot be dereferenced error in TIO which I presume means the double x does not have that method
IO x = x\y: Carry out float division then round towards -∞
NB all I'm after is to change this code to add in floor division with \
x = java.lang.Math.floor(x/y);
Relying on some Math function is arguably the best choice. "Returns the largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer."
If you need the symmetric version (truncation towards zero), you'll have to handle negative quotients:
floor(abs(x/y))*signum(x/y)
Force integer division on a double?
To force integer division, use int or long (for the calculation part); long would probably be the better choice:
x = (double)((long)x / (long)y);
That uses an explicit cast back to double for emphasis; you can just write it with the implicit cast back to double if you prefer:
x = (long)x / (long)y;
Do note that (long)y on a non-zero y can result in 0 (for instance, if y is 0.3), which then ends up being division-by-zero and thus a runtime exception.
I would like x to be the integer part of x/y
That's a different question than the title; that's not integer division, that's getting the integer part of the result of floating point division. If that's what you want, just cast the result:
x = (long)(x / y);
...(and of course the long is then implicitly cast back to double) or use Math.floor on it.
I have tried
x /= y;
x = x.intValue();
But am receiving a double cannot be dereferenced error
Right. x is a double, not Double. Primitives (like double) don't have methods, only reference types (like Double) do.
If a smaller data type is assigned to a bigger data type, there'll be no error. But the assignment of bigger to smaller gives error. In this case, you need to make compatible these data types with each other using type conversion ('x = (Type) y'). Converting a double to int is an example of assigning a bigger data type (double) to smaller (int). When we perform this operation, the double variable lost its precision and its "integer part" is assigned to the int variable.
double x = 3, y = 2;
x /= y;
int integerPart = (int) x;
System.out.println(integerPart); // Prints 1
From small to big, the numeric data types are as follows btw:
byte < short < int < long < float < double
Edit: After your last edit I realized what you actually ask. Your first expression was wrong. You don't want to find integer part of the double result of division, you want its floor. Just use java.lang.Math.floor:
double[] x = {-10, -7, 1, 3, 7.1, 9.5};
double[] y = {-10, -7, -1.7, 0.5, 7.1, 9.5};
for (int i = 0; i < y.length; i++) {
for (int j = 0; j < x.length; j++)
System.out.print(Math.floor(x[j] / y[i]) + " ");
System.out.println();
}

Integer is printed out a different value from what it actually is? [duplicate]

This question already has answers here:
How to make the division of 2 ints produce a float instead of another int?
(9 answers)
Closed 8 years ago.
So I have this code:
int x = 435;
int y = x / 2 * 5;
If I calculate y by hand, I get a result of 1087.5. But when I print the integer y out, I get the result 1085. Why is this? Shouldn't it round to either 1088 or 1087?
It's because of integer arithmetic:
int/int = int
So, 435/2 will be
435/2 = 217
And
217*5 = 1085
What can you do? Cast the values as you need:
int y = (int)((float)x / 2 * 5);
or if you want a real result, declare the variable y as float:
float y = (float)x / 2 * 5;
this saves in result of each part as an int
so
435 / 2 == 217
217 * 5 == 1085
int value of x/2=217 and 217 * 5 == 1085 is the reason
you are dividing int value x so result will be int value (int/int=int)
x/2=217
Then
217*5=1085
Try this:
int x = 435;
double y = ((double) x / 2) * 5;
y cannot be int (or else you will lose precision). Moreover, x / 2 will yield you an integer value, hence you need to cast it to double or float
Java is using integer math, this
int x = 435;
int y = x / 2 * 5;
is equivalent to
int x = 435;
int y = x / 2; // <-- 217
y *= 5; // <-- 1085
If you wanted to round the other way try,
int x = 435;
int y = (int) Math.round(((double) x / 2) * 5); // <-- 1088
the answer is correct as -:
435/2 = 217.5 since declared as int it is rounded off to 217
217*5 = 1085
which is the required answer.
When you divide 435 by 2.
It stores 217 not 217.5 and hence after multiplying 217*5= 1085
You are trying to store a float value into INT and hence getting the truncated value.
Also,without brackets, the compiler will start to execute from LHS to RHS one by one according to priority of operator.
Your code
int x = 435;
int y = x / 2 * 5;
is actually performing the following operation.
Assigning x = 435;
Dividing first y = x / 2; // This stores y= 217
And then it multiplies y=y*5; // Finally y= 1085
Using int will truncate 217.5 into 217 and hence you are getting that answer.
Use double or float for storing the kind of answer you want
int x = 435;
double y = y=(x/2)*5
This will get you the required answer.

Double not storing proper value

The code that I have,
public static void main(String[] args) {
int x = 27;
int y = 5;
double z = x / y;
System.out.println(" x = " + x + " y = "+y +" z = "+z);
}
In the above code I know that to print out the decimal place .4 for the variable z we have to use printf, but my question is why does the variable z is not storing the 5.4 and just storing 5?
I mean int / int then the out put is stored in a double, which is perfectly capable of holding decimal values but it is not, what is the logic?
This is happening because the values that you are dividing with are int and not double and they are not going to output the decimal places, to be more clear take this for example
double z = 27 /5;
same as yours
double z = 27.0/5.0;
now z = 5.4;
So this shows that the datatype that you are performing calculation with also should be the same as the datatype you are expecting the output to be.
You need to cast one of the operands to a double
double z = (double) x / y;
The reason is x / y stand-alone is an int, so it is really evaluating as 5 and then parsing to a double.
You have to cast the integers before you divide I believe.
Like this,
double z = (double) x / (double) y;
What you're doing in the line:
double z = x / y;
is integer division, and then you convert the outcome to double

Split 4 digit integer in Java

I want to split a 4-digit integer in to 2. i.e convert 1234 into two variables; x=12 and y=34. Using Java.
int four = 1234;
int first = four / 100;
int second = four % 100;
the first one works because integers are always rounded down, stripping the last two digits when divided by 100.
the second one is called modulo, dividing by 100 and then taking the rest. this strips all digits exept the first two.
Lets say you have a variable number of digits:
int a = 1234, int x = 2, int y = 2;
int lengthoffirstblock = x;
int lengthofsecondblock = y;
int lengthofnumber = (a ==0) ? 1 : (int)Math.log10(a) + 1;
//getting the digit-count from a without string-conversion
How can I count the digits in an integer without a string cast?
int first = a / Math.pow(10 , (lengthofnumber - lengthoffirstblock));
int second = a % Math.pow(10 , lengthofsecondblock);
and at the end something usefull if you have cases where the input could be negative:
Math.abs(a);
int a = 1234;
int x = a / 100;
int y = a % 100;
int i = 1234;
int x = 1234 / 100;
int y = i - x * 100;
You can treat it as a string and split it using substring(), or as an integer:
int s = 1234;
int x = s / 100;
int y = s % 100;
If it's originally an int, I'd keep it as an int and do the above.
Note that you need to consider what happens if your input is not four digit. e.g. 123.
In case you want to split the same no:
int number=1234;
int n,x,y; //(here n=1000,x=y=1)
int f1=(1234/n)*x; //(i.e. will be your first splitter part where you define x)
int f2=(1234%n)*y; //(secend splitter part where you will define y)
If you want to split the number in (12*x,34*y){where x=multiple/factor of 12 & y=multiple/factor of 34),then
1234=f(x(12),y(34))=f(36,68)
int number=1234;
int n; //(here n=1000)
int x=3;
int y=2;
int f1=(1234/n)*x; //(i.e. will be your first splitter part where you define x)
int f2=(1234%n)*y; //(secend splitter part where you will define y)
int i = 1234;
int x = i / 100;
int y = i % 100;
int num=1234;
String text=""+num;
String t1=text.substring(0, 2);
String t2=text.substring(2, 4);
int num1=Integer.valueOf(t1);
int num2=Integer.valueOf(t2);
System.out.println(num1+" "+num2);

Categories