Rounding INDArray upto certain precision

98 Views Asked by At

Looking for a similar type of function np.round_(in_array, decimals = 2) which can operate on INDArray in java. Basically want to round off all the digits in INDArray up to some precision.

Ex : Given an array

in_array = [.5538, 1.33354, .71445]

When i round it off to two-digit I am expecting the output as

array([0.55, 1.33, 0.71])
1

There are 1 best solutions below

4
Adam Gibson On

Nd4j has a normal round function but not for a specified number of decimals. If you want that just for formatting purposes we can do the following:

import org.nd4j.linalg.string;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.factory;
INDArray arr = ..;
String rounded = arr.toString(new NDArrayStrings(yourPrecision));

yourPrecision is the number of decimal places you want eg: 2,3. For your example:

import org.nd4j.linalg.string;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.factory;
INDArray arr = Nd4j.create(new double[]{.5538, 1.33354, .71445});
String rounded = arr.toString(new NDArrayStrings(2));

Edit: since it appears we need them rounded in the actual function itself you'll have to use a custom java function and iterate over the array manually. Something like:

for(int i = 0; i < arr.length(); i++) {
   arr.putScalar(i,myRounder(arr.getDouble(i),numPlaces);
}

Just be cautious of the data type when doing this.

Credit to: https://www.studytonight.com/java-examples/how-to-round-a-number-to-n-decimal-places-in-java

which gives a fairly good explanation with caveats. Your custom rounder could be something like:

public static double round(double num, int places)
{
    double scale = Math.pow(10, places);
    double roundedNum = Math.round(num * scale) / scale;
    return roundedNum;
}