I want to cast a long value to an int value and if the long value is too big to fit into an int it should just be the the biggest possible int value. My solution looks like that:
long longVar = ...;
int intVar = (int) Math.min(longVar, Integer.MAX_VALUE)
In a more general way (to include the negative maximum) it would be:
long longVar = ...;
int intVar = (int) (longVar < 0 ? Math.max(longVar, Integer.MIN_VALUE) : Math.min(longVar, Integer.MAX_VALUE));
Is there an easier way to do this, like a method in the JRE or something?
An improvement would be
int intVar = (int) Math.min(Math.max(longVar, Integer.MIN_VALUE),
Integer.MAX_VALUE));
Math.max would make [Long.Min,Long.Max] => [Int.Min, Long.Max] and whatever outcome of that, if it is greater than Int.Max will be trimmed down by the outer Math.min to [Int.Min, Int.Max].
I don't know of a ready-to-go method doing this included in java.
The java 8 method Math.toIntExact will throw an exception on overflow. And using that to do this - well, I'd consider it a misuse of exceptions. And probably less efficient than above construct.
If you can use Guava, there is a method that does exactly what you want: static int Ints.saturatedCast(long):
long longVar = ...;
int intVar = Ints.saturatedCast(longVar);
For general interest, there's the Wikipedia article on saturation arithmetic. The Intel MMX instruction set uses saturation arithmetic and I think Intel offer an SDK to allow Java developers to use MMX. I'm not sure if Guava implements its methods using this SDK (probably not).
You can also write some reusable code.
package it.stackoverflow;
public class UtilInt {
public static int getIntMaxMinLong(long longNumber){
int intNumber = 0;
if (longNumber < Integer.MIN_VALUE )
intNumber = Integer.MIN_VALUE;
else if (longNumber > Integer.MAX_VALUE)
intNumber = Integer.MAX_VALUE;
else
intNumber = (int) longNumber;
return intNumber;
}
}
You can call the method in the static way.
package it.stackoverflow;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
int intNewValue = UtilInt.getIntMaxMinLong(224748223647L);
}
}
Related
I found that Random#nextFloat returns a value between 0.0 and 1.0.
How can I get a random float value such as -72.0F or 126.232F?
I currently doing like this.
float randomFloat() {
final ThreadLocalRandom random = ThreadLocalRandom.current();
float value = random.nextFloat() * Float.MAX_VALUE;
if (random.nextBoolean()) {
value = 0 - value;
}
return value;
}
Is this right? Is there any other way to do this?
I would suggest generating a bound double and then converting to float:
return Double.valueOf(random.nextDouble(Float.MIN_VALUE, Float.MAX_VALUE)).floatValue();
The nextDouble method has been replaced in Java 8 with a method to produce a stream of doubles. So in Java 8 you would use the following equivalent:
DoubleStream randomDoubles = new Random().doubles(Float.MIN_VALUE, Float.MAX_VALUE);
Double.valueOf(randomDoubles.findAny().getAsDouble()).floatValue();
This is based on a the general idea in the prior answer, but fixes a small bug and shows how to actually write the method using JDK 1.8:
import java.util.Iterator;
import java.util.concurrent.ThreadLocalRandom;
public class Test {
public static void main(String[] args) {
Test t = new Test();
for (int i = 0; i < 100; i++) {
System.out.println(t.randomFloat());
}
}
final ThreadLocalRandom random = ThreadLocalRandom.current();
Iterator<Double> randomDoubles = random.doubles(-Float.MAX_VALUE,
Math.nextUp((double) Float.MAX_VALUE)).iterator();
float randomFloat() {
return randomDoubles.next().floatValue();
}
}
The code in the question used ThreadLocalRandom, so I did the same. The Random doubles method excludes the upper limit. In order to get the required full range, use as limit the smallest double that is greater than all finite float values. Getting an iterator<Double> seemed simpler and more direct than using findAny etc.
I would like to fit a quadratic function y = a + bx + cx^2 to some data, in such a way that c is always greater than or equal to 0 in the final result. That is, I would like to restrict my search domain over c to a particular range ([0, Double.MAX_VALUE]). Currently, I have the following code snippet:
final CurveFitter<Parametric> fitter = new CurveFitter<Parametric>(new LevenbergMarquardtOptimizer());
fitter.addObservedPoint(0, 0);
fitter.addObservedPoint(1, -1);
fitter.addObservedPoint(-1, -1);
fitter.addObservedPoint(2, -4);
fitter.addObservedPoint(-2, -4);
final double[] init = { 1, 2, 3 };
final double[] best = fitter.fit(new PositivePolynomialFunctionParametric(), init);
final PolynomialFunction fitted = new PolynomialFunction(best);
System.out.println(Arrays.toString(fitted.getCoefficients()));
where:
private static class PositivePolynomialFunctionParametric extends PolynomialFunction.Parametric {
#Override
public double value(double x, double... parameters) {
parameters[parameters.length - 1] = Math.abs(parameters[parameters.length - 1]);
return super.value(x, parameters);
}
#Override
public double[] gradient(double x, double... parameters) {
parameters[parameters.length - 1] = Math.abs(parameters[parameters.length - 1]);
return super.gradient(x, parameters);
}
}
The output makes sense:
[-1.4286835350284688, -8.489786562989103E-17, 1.0300498244514197E-11]
This seems to work in this particular application, but it is not a very elegant solution for the general case of restricting the search domain. Is there a better way to do this?
You should use one of the optimizers that implements/extends the *BoundsOptimizer types, or that supports a SimpleBounds in its OptimizationData. Section 12.4 of the user guide on optimization also mentions a way to adjust the function being optimized, but recommends using one of the bounds-supporting algorithms instead.
Just to clarify this is NOT a homework question as I've seen similar accusations leveled against other bit-hackish questions:
That said, I have this bit hack in C:
#include <stdio.h>
const int __FLOAT_WORD_ORDER = 0;
const int __LITTLE_END = 0;
// Finds log-base 2 of 32-bit integer
int log2hack(int v)
{
union { unsigned int u[2]; double d; } t; // temp
t.u[0]=0;
t.u[1]=0;
t.d=0.0;
t.u[__FLOAT_WORD_ORDER==__LITTLE_END] = 0x43300000;
t.u[__FLOAT_WORD_ORDER!=__LITTLE_END] = v;
t.d -= 4503599627370496.0;
return (t.u[__FLOAT_WORD_ORDER==__LITTLE_END] >> 20) - 0x3FF;
}
int main ()
{
int i = 25; //Log2n(25) = 4
int j = 33; //Log2n(33) = 5
printf("Log2n(25)=%i!\n",
log2hack(25));
printf("Log2n(33)=%i!\n",
log2hack(33));
return 0;
}
I want to convert this to Java. So far what I have is:
public int log2Hack(int n)
{
int r; // result of log_2(v) goes here
int[] u = new int [2];
double d = 0.0;
if (BitonicSorterForArbitraryN.__FLOAT_WORD_ORDER==
BitonicSorterForArbitraryN.LITTLE_ENDIAN)
{
u[1] = 0x43300000;
u[0] = n;
}
else
{
u[0] = 0x43300000;
u[1] = n;
}
d -= 4503599627370496.0;
if (BitonicSorterForArbitraryN.__FLOAT_WORD_ORDER==
BitonicSorterForArbitraryN.LITTLE_ENDIAN)
r = (u[1] >> 20) - 0x3FF;
else
r = (u[0] >> 20) - 0x3FF;
return r;
}
(Note it's inside a bitonic sorting class of mine...)
Anyhow, when I run this for the same values 33 and 25, I get 52 in each cases.
I know Java's integers are signed, so I'm pretty sure that has something to do with why this is failing. Does anyone have any ideas how I can get this 5-op, 32-bit integer log 2 to work in Java?
P.S. For the record, the technique is not mine, I borrowed it from here:
http://graphics.stanford.edu/~seander/bithacks.html#IntegerLogIEEE64Float
If you're in Java, can't you simply do 31 - Integer(v).numberOfLeadingZeros()? If they implement this using __builtin_clz it should be fast.
I think you did not get the meaning of that code. The C code uses a union - a struct that maps the same memory to two or more different fields. That makes it possible to access the storage allocated for the double as integers. In your Java code, you don't use an union but two different variables that are mapped to different parts of memory. This makes the hack fail.
As Java has no unions, you had to use serialization to get the results you want. Since that is quite slow, why not use another method to calculate the logarithm?
You are using the union to convert your pair of ints into a double with the same bit pattern. In Java, you can do that with Double.longBitsToDouble, and then convert back with Double.doubleToLongBits. Java is always (or at least gives the impression of always being) big-endian, so you don't need the endianness check.
That said, my attempt to adapt your code into Java didn't work. The signedness of Java integers might be a problem.
Is there a way to create a 128 bit object in java, that can be bit manipulated the same way as a long or int? I want to do 32 bit shifts and i want to be able to do a bit OR operation on the whole 128 bit structure.
Here, I present to you... an old idea. Now it's awfully downgraded (no code enhancer, no nothing) to simple 128 bit thingie that should be super fast, though. What I truly want is a ByteBuffer based array of C alike Struct but fully usable in java.
The main idea is allocating more than a single object at a time and using a pointer to the array. Thus, it greatly conserves memory and the memory is allocated in continuous area, so less cache misses (always good).
I did some moderate testing (but the code is still untested).
It does allow basic operations like add, xor, or, set/get with 128 bit numbers.
The standard rule: less documentation than expected applied unfortunately.
Adding extra code for extra operations should be straight forward.
Here is the code, look at main method for some usage. Cheers!
package bestsss.util;
import java.util.Random;
public class Bitz {
final int[] array;
private Bitz(int n){
array=new int[n<<2];
}
public int size(){
return size(this.array);
}
private static int size(int[] array){
return array.length>>2;
}
/**
* allocates N 128bit elements. newIdx to create a pointer
* #param n
* #return
*/
public static Bitz allocate(int n){
return new Bitz(n);
}
/**
* Main utility class - points to an index in the array
* #param idx
* #return
*/
public Idx newIdx(int idx){
return new Idx(array).set(idx);
}
public static class Idx{
private static final long mask = 0xFFFFFFFFL;
//dont make the field finals
int idx;
int[] array;//keep ref. here, reduce the indirection
Idx(int[] array){
this.array=array;
}
public Idx set(int idx) {
if (Bitz.size(array)<=idx || idx<0)
throw new IndexOutOfBoundsException(String.valueOf(idx));
this.idx = idx<<2;
return this;
}
public int index(){
return idx>>2;
}
public Idx shl32(){
final int[] array=this.array;
int idx = this.idx;
array[idx]=array[++idx];
array[idx]=array[++idx];
array[idx]=array[++idx];
array[idx]=0;
return this;
}
public Idx shr32(){
final int[] array=this.array;
int idx = this.idx+3;
array[idx]=array[--idx];
array[idx]=array[--idx];
array[idx]=array[--idx];
array[idx]=0;
return this;
}
public Idx or(Idx src){
final int[] array=this.array;
int idx = this.idx;
int idx2 = src.idx;
final int[] array2=src.array;
array[idx++]|=array2[idx2++];
array[idx++]|=array2[idx2++];
array[idx++]|=array2[idx2++];
array[idx++]|=array2[idx2++];
return this;
}
public Idx xor(Idx src){
final int[] array=this.array;
int idx = this.idx;
int idx2 = src.idx;
final int[] array2=src.array;
array[idx++]^=array2[idx2++];
array[idx++]^=array2[idx2++];
array[idx++]^=array2[idx2++];
array[idx++]^=array2[idx2++];
return this;
}
public Idx add(Idx src){
final int[] array=this.array;
int idx = this.idx+3;
final int[] array2=src.array;
int idx2 = src.idx+3;
long l =0;
l += array[idx]&mask;
l += array2[idx2--]&mask;
array[idx--]=(int)(l&mask);
l>>>=32;
l += array[idx]&mask;
l += array2[idx2--]&mask;
array[idx--]=(int)(l&mask);
l>>>=32;
l += array[idx]&mask;
l += array2[idx2--]&mask;
array[idx--]=(int)(l&mask);
l>>>=32;
l += array[idx]&mask;
l += array2[idx2--];
array[idx]=(int)(l&mask);
// l>>>=32;
return this;
}
public Idx set(long high, long low){
final int[] array=this.array;
int idx = this.idx;
array[idx+0]=(int) ((high>>>32)&mask);
array[idx+1]=(int) ((high>>>0)&mask);
array[idx+2]=(int) ((low>>>32)&mask);
array[idx+3]=(int) ((low>>>0)&mask);
return this;
}
public long high(){
final int[] array=this.array;
int idx = this.idx;
long res = (array[idx]&mask)<<32 | (array[idx+1]&mask);
return res;
}
public long low(){
final int[] array=this.array;
int idx = this.idx;
long res = (array[idx+2]&mask)<<32 | (array[idx+3]&mask);
return res;
}
//ineffective but well
public String toString(){
return String.format("%016x-%016x", high(), low());
}
}
public static void main(String[] args) {
Bitz bitz = Bitz.allocate(256);
Bitz.Idx idx = bitz.newIdx(0);
Bitz.Idx idx2 = bitz.newIdx(2);
System.out.println(idx.set(0, 0xf));
System.out.println(idx2.set(0, Long.MIN_VALUE).xor(idx));
System.out.println(idx.set(0, Long.MAX_VALUE).add(idx2.set(0, 1)));
System.out.println("==");
System.out.println(idx.add(idx));//can add itself
System.out.println(idx.shl32());//left
System.out.println(idx.shr32());//and right
System.out.println(idx.shl32());//back left
//w/ alloc
System.out.println(idx.add(bitz.newIdx(4).set(0, Long.MAX_VALUE)));
//self xor
System.out.println(idx.xor(idx));
//random xor
System.out.println("===init random===");
Random r = new Random(1112);
for (int i=0, s=bitz.size(); i<s; i++){
idx.set(i).set(r.nextLong(), r.nextLong());
System.out.println(idx);
}
Idx theXor = bitz.newIdx(0);
for (int i=1, s=bitz.size(); i<s; i++){
theXor.xor(idx.set(i));
}
System.out.println("===XOR===");
System.out.println(theXor);
}
}
Three possibilities have been identified:
The BitSet class provides some of the operations that you need, but no "shift" method. To implement this missing method, you'd need to do something like this:
BitSet bits = new BitSet(128);
...
// shift left by 32bits
for (int i = 0; i < 96; i++) {
bits.set(i, bits.get(i + 32));
}
bits.set(96, 127, false);
The BigInteger class provides all of the methods (more or less), but since BigInteger is immutable, it could result in an excessive object creation rate ... depending on how you use the bitsets. (There is also the issue that shiftLeft(32) won't chop off the leftmost bits ... but you can deal with this by using and to mask out the bits at index 128 and higher.)
If performance is your key concern, implementing a custom class with 4 int or 2 long fields will probably give best performance. (Which is actually the faster option of the two will depend on the hardware platform, the JVM, etc. I'd probably choose the long version because it will be simpler to code ... and only try to optimize further if profiling indicated that it was a potentially worthwhile activity.)
Furthermore, you can design the APIs to behave exactly as you require (modulo the constraints of Java language). The downside is that you have to implement and test everything, and you will be hard-wiring the magic number 128 into your code-base.
There is no longer data type than long (I have logged this as an RFE along with a 128 bit floating point ;)
You can create an object with four 32-bit int values and support these operations fairly easily.
You can't define any new types to which you could apply Java's built-in bitwise operators.
However, could you just use java.math.BigInteger? BigInteger defines all of the bit-wise operations that are defined for integral types (as methods). This includes, for example, BigInteger.or(BigInteger).
No.
Sorry there isn't a better answer.
One approach may be to create a wrapper object for two long values and implement the required functionality while taking signedness of the relevant operators into account. There is also BigInteger [updated from rlibby's answer], but it doesn't provide the required support.
Happy coding.
Perhaps BitSet would be useful to you.
It has the logical operations, and I imagine shifting wouldn't be all that hard to implement given their utility methods.
Afaik, the JVM will just convert whatever you code into 32 bit chunks whatever you do. JVM is 32 bit. I think even 64 bit version of JVM largely processes in 32 bit chunks. It certainly should to conserve memory... You're just going to slow down your code as the JIT tries to optimise the mess you create. In C/C++ etc. there's no point doing this either as you will still have impedance from the fact that it's 32 or 64 bit registers in the hardware you're most likely using. Even the Intel Xenon Phi (has 512bit vector registers) is just bunches of 32 and 64 bit elements.
If you want to implement something like that, you could try to do it in GLSL or OpenCL if you have GPU hardware available. In 2015 Java Sumatra will be released as part of Java 9, at least that's the plan. Then you will have the ability to integrate java with GPU code out of the box. That IS a big deal, hence the illustrious name!
I want to compute the function H(n)
where
H(0)=0;
H(i)=H(i-1)×A+Ci mod B;
10<=A,B<=10^15;
C is an array of n elements
The following code takes too much time...any better way of doing this?
public BigInteger H(int no) {
if(no>0) {
bi=H(no-1);
bi=bi.multiply(BigInteger.valueOf(A));
bi=bi.add(BigInteger.valueOf(c[no-1]));
bi=bi.remainder(BigInteger.valueOf(B));
return bi;
}
return BigInteger.ZERO;
}
Try using a dynamic programming approach. Rather than using recursion, loop starting at the initial case H(0) and moving up from there. Example:
public static BigInteger H(BigInteger[] c, int no, BigInteger A, BigInteger B) {
if (c.length < no - 1) {
throw new IllegalArgumentException("no is too large");
}
BigInteger bi = BigInteger.ZERO; // Initial case H(0) = 0
for (int i = 1; i <= no; i++) { // From H(1) -> H(no)
bi = bi.multiply(A).add(c[i - 1]).remainder(B);
}
return bi;
}
Try not using the remainder every iteration, it uses division which is VERY slow.
You should also not use BigInteger.valueOf() every iteration. Only create A and B as BigIntegers one time and save them, there is no need for doing it more times.
Yeah, welcome to the world of BigIntegers.
One thing I remember is that you can do two paths for this:
1) A slow path with BigIntegers
2) A fast path with double primitive types when both the arguments are less than Max Double.
That should pump up the speed a little bit.
Tell us here how it went and post times if you can. This is really interesting.