MCPcopy Create free account
hub / github.com/OpenSourcePhysics/osp / findNearestXIndex0

Method findNearestXIndex0

src/test/PerformanceTests.java:87–132  ·  view source on GitHub ↗
(double x, double[] xpoints, double[] ypoints, int len, double min, double max)

Source from the content-addressed store, hash-verified

85 }
86
87 public static int findNearestXIndex0(double x, double[] xpoints, double[] ypoints, int len, double min, double max) {
88
89 x = Math.min(max, Math.max(min, x));
90
91 // sort x data, keeping only points for which the y-value is not NaN
92 ArrayList<Double> valid = new ArrayList<Double>();
93 for (int i = 0; i < len; i++) {
94 if (Double.isNaN(ypoints[i]))
95 continue;
96 valid.add(xpoints[i]);
97 }
98 Double[] sorted = valid.toArray(new Double[valid.size()]);
99 java.util.Arrays.sort(sorted);
100 int last = sorted.length - 1;
101
102 // check if pixel outside data range
103 if (x < sorted[0]) {
104 return 0;
105 }
106 if (x >= sorted[last]) {
107 return last;
108 }
109
110 // look thru sorted data to find point nearest x
111 for (int i = 1; i < sorted.length; i++) {
112 if (x >= sorted[i - 1] && x < sorted[i]) {
113 // found it
114 if (sorted[i - 1] < min) {
115 x = sorted[i];
116 } else if (sorted[i] > max) {
117 x = sorted[i - 1];
118 } else {
119 x = (Math.abs(x - sorted[i - 1]) < Math.abs(x - sorted[i])) ? sorted[i - 1] : sorted[i];
120 }
121
122 // find index of first data point with this value of x
123 for (int j = 0; j < xpoints.length; j++) {
124 if (xpoints[j] == x && !Double.isNaN(ypoints[j])) {
125 return j;
126 }
127 }
128 return -1;
129 }
130 }
131 return -1; // none found (should never get here)
132 }
133
134
135}

Callers 1

Calls 7

minMethod · 0.80
maxMethod · 0.80
isNaNMethod · 0.80
toArrayMethod · 0.80
absMethod · 0.80
addMethod · 0.45
sortMethod · 0.45

Tested by

no test coverage detected