I want my function to take a value x and find the in between values of my array shown below:
double[] xlist = {51.8, 10.3, 5.1, 2.6, 1.7, 1.29, 1.03, 0.86, 0.65, 0.52, 0.43, 0.37, 0.32, 0.29};
I am using a derivative of the bisection method to find these "high" and "low" values but there is something wrong with my code. My code is shown below:
public static void main(String[] args){
double[] xlist = {51.8, 10.3, 5.1, 2.6, 1.7, 1.29, 1.03, 0.86, 0.65, 0.52, 0.43, 0.37, 0.32, 0.29};
double x = 0.9; //or whatever declare x to equal
int high = xlist.length;
int mid = 0, low = 0;
while (low != high) {
mid = (low + high) / 2;
if (xlist[mid] > x) {
low = mid + 1;
} else {
high = mid;
}
}
System.out.println(xlist[mid - 1] + "\n" + x + "\n" + xlist[mid]);
}
My console output is shown below:
51.8
12.0
10.3
It works but when I change the x value to say 9.9 I get:
5.1
9.9
2.6
What am I doing wrong? Any help is much appreciated.
When you are dividing (low + high)/2
you are assigning the result into and int value and are losing some data. What I have done below is change the data type of high, mid, and low to "double" and then cast the values to an int when referencing elements in your double array. Please try the code below.
double[] xlist = {51.8, 10.3, 5.1, 2.6, 1.7, 1.29, 1.03, 0.86, 0.65, 0.52, 0.43, 0.37, 0.32, 0.29};
double x = 9.9; //or whatever declare x to equal
double high = xlist.length;
double mid = 0.0, low = 0.0;
while (low != high) {
mid = (low + high) / 2;
if (xlist[(int)mid] > x) {
low = mid + 1;
} else {
high = mid;
}
}
System.out.println(xlist[(int)mid - 1] + "\n" + x + "\n" +
xlist[(int)mid]);