How to create a fast pseudo-random hashCode? - java

I am working on a Java to WebAssembly compiler (JWebAssembly). I need to replace native code with things that can run in WebAssembly.
For java.lang.Object.hashCode() and java.lang.System.identityHashCode() I use currently the follow JavaScript code:
identityHashCode = (o) => {
var h = o[1];
while( h == 0 ){
o[1] = h = Math.round( ( Math.random() - 0.5 ) * 0xffff );
}
return h;
}
But this required for every new hashCode a round trip to the JavaScript scope which cost performance. With a browserless environment (without JavaScript) like WASI this will not work. That I search for a poor replacement.
I think a hashCode:
does not need be really random
the values must only be well distributed
Is this correct?
The follow Java code should be good enough.
private static int globalHash = (int)System.currentTimeMillis();
private int hashCode;
public int hashCode() {
if( hashCode == 0 ) {
hashCode = globalHash = (globalHash + 1) * 31;
}
return hashCode;
}
Is this good enough for a generic hashCode function? Would there a better implementation?

Related

Euler's Method in java

I have written an Euler's Method code to find an approximate value for x(10) and compare it to the value of x(10) given by the exact solution given in separable ODE. However, my code displays a chaotic number for x(10). Can you please identify a major error.
Thank you.
//#(#)euler.java
//This method attempts to find solutions to dx/dt = (e^t)(sin(x)) via
//Euler's iterative method and find an approximate value for x(10)
import java.text.DecimalFormat;
public class euler
{
public static void main(String[] Leonhard)
{
DecimalFormat df = new DecimalFormat("#.0000");
double h = (1.0/3.0); // h is the step-size
double t_0 = 0; // initial condition
double x_0 = .3; // initial condition
double x_f = 10; // I want to find x(10) using this method and compare it to an exact value of x(10)
double[] t_k;
t_k = new double[ (int)( ( x_f - x_0 ) / h ) + 1 ] ; // this two arrays hold the values of x_k and t_k
double[] x_k;
x_k = new double[ (int)( ( x_f - x_0 ) / h ) + 1 ] ;
int i; // the counter
System.out.println( "k\t t_k\t x_k" ); // table header
for ( i = 0; k < (int)( ( x_f - x_0 ) / h ) + 1; i++ )
{
if ( i == 0 ) // this if statement handles the initial conditions
{
t_k[i] = t_0;
x_k[i] = x_0;
}
else if ( i > 0 )
{
t_k[i] += i*h;
x_k[i] = x_k[i-1] + h*( Math.exp(t_k[i-1]))*(Math.sin(x_k[i-1]) );
}
System.out.println( k + " " + df.format(t_k[i]) + " " + df.format( x_k[i]) );
}
}
}
Your code seems to work. The problem is that Euler's method is a fairly simplistic way of approximately integrating a differential equation. Its accuracy is strongly dependent upon the step size you're using, as you noticed.
I ran your code and compared with another implementation of the same algorithm. The results overlap in the regime where the approximation is working, and quite a while beyond. They only differ once the method breaks down strongly:
A thing to note is that the Euler method doesn't work very well for this particular differential equation, for the point you wish to reach. A step size of 1/3 is much too big to begin with, but even if you choose a much smaller step size, e.g 1/10000, the method tends to break down before reaching t=10. Something like exp(t)sin(x) is hard to deal with. The real solution becomes flat, approaching pi, so sin(x) should go to zero, making the derivative zero as well. However, exp(t) blows up, so the derivative is numerically unstable.

Lazy fibonnaci series

I have just started learning haskell and wondering if there is any way we can implement below fibonacci series in C# or java or other non-lazy imperative languages.
In haskell we can succinctly generate fibonacci series with the below one liner
fibonacci = 0 : 1 : zipWith (+) fibonacci (tail fibonacci)
Question - I understand that as C#/Java etc eagerly evaluates, the above would probably go to an infinite loop. But what i do not understand is that even if we use a thunk, how can we can create a self referencing data structure which changes as we iterate over it (using recursion).
Appreciate if you could share some snippet
The Scala API docs for Stream contains an example on how to do this in Scala:
val fibs: Stream[BigInt] = BigInt(0) #:: BigInt(1) #:: fibs.zip(fibs.tail).map { n => n._1 + n._2 }
Edit: To implement memoization in a language which doesn't have it built-in like Haskell, you would obviously need to use mutation (an array or a map). For example:
val fib: Int => Int = {
val m = ArrayBuffer(0, 1)
x => if (x < m.size) m(x) else {
println("Calculating " + x + "...")
val r = fib(x - 2) + fib(x - 1)
m += r
r
}
}
This can still be considered to be a pure function as there are no observable side effects (besides runtime performance) in a single threaded environment.
In C# you can implement this in the next way:
IEnumerable <int> Fibonacci() {
var a = 0;
var b = 1;
while (true) {
var t = b;
yield return b = a + b;
a = t;
}
}

Test Case failing when expected is equal to output

Before I get into detail, YES this is a HOMEWORK ASSIGNMENT. NO I DON'T WANT ANSWERS, JUST TIPS and/or Suggestions to try this or that.
The problem introduces with this:
Create a class, ExactNumber, that uses two long properties named left
and right (representing the portion of the number that is to the left
and right of the decimal point respectively). For example, 3.75 would
be represented by new ExactNumber(3, 7500000000000000L). Note the L on
the end which tells Java the large number is a long. This translates
to: 3 + 7500000000000000/10000000000000000 = 3.75
Here is my code:
public class ExactNumber {
private long left;
private long right;
public ExactNumber(long left, long right) {
this.left = left;
this.right = right;
}
public String toString() {
return String.valueOf(doubleValue());
}
public double doubleValue() {
return ((double) left + (double) (right/ 100000000000000L) / 100);
}
public int compareTo (ExactNumber exactNumber) {
if(exactNumber.left < left) {
return 1;
}
else if (exactNumber.left == left) {
if (exactNumber.right < right) {
return 1;
}
else if (exactNumber.right == right) {
return 0;
}
else {
return -1;
}
}
else {
return -1;
}
}
public boolean equal(ExactNumber thisobject) {
if (thisobject instanceof ExactNumber) {
if (thisobject.doubleValue() == this.doubleValue()) {
return true;
}
else {
return false;
}
}
else {
return false;
}
}
public double add(ExactNumber exactNumber) {;
return ((left+exactNumber.left) + (double)((right+exactNumber.right)*1E-16));
}
}
My problem are the tests coming up as an error when the expected value is equal to the actual value. Here are the test cases (NOTE: there are more test cases, but they pass the JUnit test):
public class TestExactNumber extends TestCase {
ExactNumber threesevenfive = new ExactNumber(3, 7500000000000000L);
ExactNumber threesevenfive_andalittlebit = new ExactNumber(3, 7500000000000001L);
ExactNumber threesevenfive_dupe = new ExactNumber(3, 7500000000000000L);
ExactNumber ten = new ExactNumber(10, 0);
ExactNumber thirteensevenfive = new ExactNumber(13, 7500000000000000L);
ExactNumber sevenfifty = new ExactNumber(7, 5000000000000000L);
public void test_equals() {
assertFalse(threesevenfive.equals(threesevenfive_andalittlebit));
assertEquals(threesevenfive, threesevenfive_dupe);
}
public void test_add() {
assertEquals(threesevenfive.add(ten), thirteensevenfive);
assertEquals(threesevenfive.add(threesevenfive), sevenfifty);
The assertEquals above failed in the JUnit test, but says like (for an example) expected = 13.75 and actual = 13.75.
Any tips or hints at what I need to do with my code is greatly appreciated. And thank you in advanced.
NOTES:
According to my instructor, I should not be using the doubleValue method to implement my equals method. I know that I do have it in my code, but that was prior to the tip the instructor gave me and I am just unsure about how to change it.
I am using eclipse for java to code this.
Your equal Method is never used. The Java Method used by assertEquals() is called equalS (and you have to override the equals() method derived from Object).
Therefore, the assertion will use equals inherited from Object, which will compare the actual instances rather than using YOUR equal method which will compare the objet values. And since they are two different INSTANCES, they are not equal.
Finally, the two instances will be plotted with toString() resulting in expected = 13.75 and actual = 13.75. (Because your toString() returns only the values, ignoring the difference between instances)
Your Instructors Response:
A Long in Java is a 64 bit long number. Double in Java is implemented with the IEEE754 Standard, which only leaves 52 bit for the mantissa. Meaning: Any conversion of a Long Number to a double, where the Long Number has set bits on bit 53 to 63 - will cause the exponent to be shifted in a way, that you loose precision arround the LSBs - resulting in an unprecice Double Value.
Therefore comparing the double values to determine equality is not sufficent for your desired Design of a "Exact Number".
Example:
Long bigLong = 1L<<51; //picked 51: 52 and 53 already causing rounding issues.
Long long1 = bigLong + 1L;
Long long2 = bigLong + 2L;
System.out.println(long1+" -> " + long1.doubleValue());
System.out.println(long2+" -> " + long2.doubleValue());
//false, enough precision to preserve bit "0" and "1".
System.out.println(long1.doubleValue()==long2.doubleValue());
Output:
2251799813685262 -> 2.251799813685262E15
2251799813685263 -> 2.251799813685263E15
false
When setting bit 54:
Long bigLong = 1L<<54;
Long long1 = bigLong + 1L;
Long long2 = bigLong + 2L;
System.out.println(long1+" -> " + long1.doubleValue());
System.out.println(long2+" -> " + long2.doubleValue());
System.out.println(long1.doubleValue()==long2.doubleValue());
Output:
18014398509481985 -> 1.8014398509481984E16
18014398509481986 -> 1.8014398509481984E16
true
Note the Exponent beeing increased from 15 to 16, which will cut off the difference of "1" between both longs.
To solve this, you can compare left1 to left2 and right1 to right2 without converting it to a double.
Your equal method should ideally test every necessary value in your class. In this case, it should be checking to see if your left and right values are the same between the two objects. If they are the same, then you can consider the objects to be equal.
In your case, you should probably put a debug point in your equals method to see why the function is returning back a false.
Try using Eclipse's built in functionality to create equals and hashcode methods for you. You can create that by going to Source->Generate hashCode() and equals(). The methods will be very different from what you have created.
Another thing, in your AssertEquals method, make sure both the values passed in are of the same type. In your case, you're checking a Double with an ExactNumber object. They will definitely not be the same. You need to either
Change your Add method to return a ExactNumber object
Have a method in your ExactNumber class called getDouble() and use that as the second parameter instead.
Hope this helps.

What is the purpose of variable duplication in a method?

I see this [below] all over in the Android code (and some other code sources). What is its point or purpose?
class Foo {
int mBar = 1337;
static void main(String... args) {
System.out.println(isFubar());
}
boolean isFubar() {
int ret = mBar; // <--- Focus of attention
if (ret == 666)
return true;
else
return false;
}
}
It seems like a waste of time and resources. mBar clearly isn't being modified. There is no risk of it being modified (in the given context), so why would one duplicate the primitive just to preform a noninvasive check on it and return?
EDIT Specific example from the class CellLayout in the Android Source
public void cellToRect(int cellX, int cellY, int cellHSpan, int cellVSpan, RectF dragRect) {
final boolean portrait = mPortrait; <--- Here it is
final int cellWidth = mCellWidth;
final int cellHeight = mCellHeight;
final int widthGap = mWidthGap;
final int heightGap = mHeightGap;
final int hStartPadding = portrait ? mShortAxisStartPadding : mLongAxisStartPadding;
final int vStartPadding = portrait ? mLongAxisStartPadding : mShortAxisStartPadding;
int width = cellHSpan * cellWidth + ((cellHSpan - 1) * widthGap);
int height = cellVSpan * cellHeight + ((cellVSpan - 1) * heightGap);
int x = hStartPadding + cellX * (cellWidth + widthGap);
int y = vStartPadding + cellY * (cellHeight + heightGap);
dragRect.set(x, y, x + width, y + height);
}
Perhaps for multi-threading. If the value of mPortrait changed between the following two lines you would have mixed results.
final int hStartPadding = mPortrait ? mShortAxisStartPadding : mLongAxisStartPadding;
final int vStartPadding = mPortrait ? mLongAxisStartPadding : mShortAxisStartPadding;
For example:
final int hStartPadding = true ? mShortAxisStartPadding : mLongAxisStartPadding;
// somehwere else: mPortraint = false
final int vStartPadding = false ? mLongAxisStartPadding : mShortAxisStartPadding;
A few ideas come to mind.
The expression needed to retrieve the class member variable might be really complicated (your example is not), so saving it in a local variable might be more readable.
It is possible that storing it in a local variable is more efficient, especially if the method has to access the value more than once. (Your example does not do this.)
Retrieving the value once gets its value at that moment in time, and not some later value that another thread may have modified in the meantime.
Storing it in a local variable makes it easy to examine with a debugger.
For your particular example, only reason (4) makes any sense.
I use it so i can modify the variable in recursion or loops and not mess with the original one. It also helps with passing the variables between classes and other methods.
Also, if it is changed while the method is running, the method will not mess up, it will continue with the variables it started with. I had this major problem while multi-threading my graphics printing and code. The code would change variables and weird stuff would happen on the screen.
I don't know about hardware or speed, but on the code side, it makes it very simple and flexible in many cases.

Java convert float to integer

I want to do an operation like this : if the given float numbers are like 1.0 , 2.0 , 3.0 , I want to save them to database as integer (1,2,3 ), if they are like 1.1 , 2.1 , ,3.44 , I save them as float. what's the best solution for this problem using java ? The corresponding field in database is type of varchar.
Just try int i = (int) f;.
EDIT : I see the point in the question. This code might work :
int i = (int) f;
String valToStore = (i == f) ? String.valueOf(i) : String.valueOf(f);
String result = "0";
if (floatVar == Math.floor(floatVar)) {
result = Integer.toString((int) floatVar);
} else {
result = Float.toString(floatVar);
}
The if-clause checks whether the number is a whole number - i.e. if it is equal to the result of rounding it down to the closest whole value.
But this is very odd requirement indeed, and perhaps you should reconsider the need for such a thing.
Seems like you want to save Floats with no trailing numbers as Integers, while saving those with significant trailing numbers as Floats. I would rather just save it all as Float to the DB, but it's your question so here's my answer:
/**
* Method to determine if trailing numbers are significant or not. Significant
* here means larger than 0
*
* #param fFloat
* #return
*/
public static boolean isTrailingSignificant(Float fFloat)
{
int iConvertedFloat = fFloat.intValue();// this drops trailing numbers
// checks if difference is 0
return ((fFloat - iConvertedFloat) > 0);
}
This is how you would use this method:
Number oNumToSave = null;
if (isTrailingSignificant(fFloat))
{
// save float value as is
oNumToSave = fFloat;
}
else
{
// save as int
oNumToSave = fFloat.intValue();// drops trailing numbers
}
After that, you can do the database operation using the variable oNumToSave.
Not sure this is the best solution, but you can try to write a method like this :
String convertToString(Float f) {
if (f.toString().endsWith(".0"))
return f.intValue().toString();
else
return f.toString();
}
Kotlin:
val mAmount = 3.0
val intAmount = mAmount.toInt()
val amountToDisplay = if (intAmount.compareTo(mAmount) == 0) intAmount.toString() else java.lang.String.valueOf(mAmount)

Categories