I'm not sure if this is an issue with my formula or my thought process. This is an exercise from CodeAbbey so not looking for the specific answer, just a push in the right direction.
I understand binary searches when it comes to array's. Here we're trying to use it to solve an equation. This is the example:
A * x + B * sqrt(x ^ 3) - C * exp(-x / 50) - D = 0
This is my formula where mid serves as x:
double result = (((a * mid) + (b * (Math.sqrt(Math.pow(mid, 3.0)))) - (c * (Math.exp(-mid / 50)) - d)));
This is a test case they give:
Data:
1
0.59912051 0.64030348 263.33721367 387.92069617
Result should be:
73.595368554162
I think it's my formula. If I plug in that result I do not get 0 as I assume I should.
Which is why I never get exited from my while loop.
package com.secryption.CA34BinarySearch;
import java.util.Scanner;
/**
* Created by bmarkey on 11/11/2015.
*/
public class BinarySearch {
public static void main(String[] args) {
Scanner scanner1 = new Scanner(System.in);
System.out.println("Enter Data: ");
int testCases = scanner1.nextInt();
for (int i = 0; i < testCases; i++) {
double a = scanner1.nextDouble();
double b = scanner1.nextDouble();
double c = scanner1.nextDouble();
double d = scanner1.nextDouble();
boolean solved = false;
double upperBound = (c + d) / (a + b);
double lowerBound = 0;
double mid;
while (!(solved)) {
mid = (upperBound + lowerBound) / 2.0;
double result = ((a * mid) + (b * (Math.sqrt(Math.pow(mid, 3.0)))) - (c * (Math.exp(-mid / 50)) - d));
if (result > 0) {
upperBound = mid;
} else if (result < 0) {
lowerBound = mid;
} else {
System.out.println(mid);
solved = true;
}
}
}
}
}