Java function to maintain detail

I need to preserve granularity in fuzzy work, so I made a function that receives as parameters:

  • granularity (double between 0 and 1, 0 not included)
  • value for conversion, if necessary (this double is greater than 0)

And returns a new value with the correct granularity.

This is the function that I have:

public static double preserveGranularity(double granul, double value){ double integerValue= (double)(int)value; if(granul == 1) return integerValue; double decimal = value - integerValue; long factor = Math.round(decimal/granul); return integerValue + granul*factor; } 

Examples:

  • preserveGranularity (0.25, 7.7) should return 7.75
  • preserveGranularity (0.01, 0.009) should return 0.01

It works well for most values, but it does not work for everyone (for example: preserveGranularity (0.2, 0.57) = 0.6000000000000001, it should return 0.6)

Hi

PS Sorry for any mistake I made on this issue, this is my first here.

+4
source share
2 answers

You cannot achieve this with double - because it is not accurate enough.
double - not real numbers. To represent them, there is only a finite number of bits, while there is an infinite number of real (or even rational) numbers, so such rounding errors are expected.

I think that you are looking for BigDecimal , which allows you to control the details as you want, for example with round() .

+4
source

Floating-point calculations are not accurate (a computer can only represent as many digits). This means that somewhere in your division / multiplication / rounding / subtraction / addition operations, you are losing accuracy.

+1
source

Source: https://habr.com/ru/post/1411845/


All Articles