0

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])
desertnaut
  • 57,590
  • 26
  • 140
  • 166
Programmer
  • 165
  • 1
  • 1
  • 7

1 Answers1

0

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;
}

Adam Gibson
  • 3,055
  • 1
  • 10
  • 12
  • I do not want it for formatting purposes but want to use it in manipulation going ahead on this INDArray object. – Programmer Jan 15 '22 at 09:36
  • Then yeah the closest thing we have is the normal round method. You'll have to implement your own using a for loop. You can iterate over all numbers and apply a decimal rounding function to the number of places. There's a number of tutorials on google for this. – Adam Gibson Jan 15 '22 at 10:18
  • Yes, that is a possible option but not efficient. I was looking at some property of INDArray which can be modified to set a precision that will be used while creating the array – Programmer Jan 15 '22 at 13:44
  • I'm not sure what your use case is but we have a round function sitting right in the framework that does what you need minus the precision. I don't know what to tell you unless you want to implement the op or file an issue and we can look in to it. That version can be found here: https://github.com/eclipse/deeplearning4j/blob/master/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/ops/transforms/Transforms.java#L649 – Adam Gibson Jan 15 '22 at 13:59