Posted By

rtperson on 08/10/12


Tagged

math


Versions (?)

Scaling Values into a range between 0 and 1


 / Published in: Java
 

You have to use float or double for the returned value, since the scale occurs in a continuous function.

  1. public double[] scaleValues(double[] vals) {
  2. double[] result = new double[vals.length];
  3. double min = minArray(vals);
  4. double max = maxArray(vals);
  5. double scaleFactor = max - min;
  6. // scaling between [0..1] for starters. Will generalize later.
  7. for (int x = 0; x < vals.length; x++) {
  8. result[x] = ((vals[x] - min) / scaleFactor);
  9. }
  10. return result;
  11. }
  12.  
  13. // The standard collection classes don't have array min and max.
  14. public double minArray(double[] vals) {
  15. double min = vals[0];
  16. for (int x = 1; x < vals.length; x++) {
  17. if (vals[x] < min) {
  18. min = vals[x];
  19. }
  20. }
  21. return min;
  22. }
  23.  
  24. public double maxArray(double[] vals) {
  25. double max = vals[0];
  26. for (int x = 1; x < vals.length; x++) {
  27. if (vals[x] > max) {
  28. max = vals[x];
  29. }
  30. }
  31. return max;
  32. }

Report this snippet  

You need to login to post a comment.