I modified the code in the following manner:
public class BlackScholesBinary {
// Black-Scholes formula (calculates the BS option value, to which the binary search below will be used to find the volatility)
public static double callPrice(double s, double x, double r, double sigma, double t) {
double a = (Math.log(s/x) + (r + sigma * sigma/2) * t) / (sigma * Math.sqrt(t));
double b = a - sigma * Math.sqrt(t);
return s * Gaussian.Phi(a) - x * Math.exp(-r * t) * Gaussian.Phi(b);
}
public static double getSigma(double s, double x, double r, double t, double price, double lo, double hi, double delta) { //delta = tolerance
// lo = 0.0;
// hi = 100000.0;
// delta = 0.01;
double mid = lo + (hi - lo) / 2;
if (price < callPrice(s, x, r, mid, t)) return getSigma(s, x, r, t, price, lo, mid, delta);
else if (price > callPrice(s, x, r, mid, t)) return getSigma(s, x, r, t, price, mid, hi, delta);
else if (price == callPrice(s, x, r, mid, t) && (hi - lo < delta)) return mid;
else return Double.NaN;
}
public static void main(String[] args) {
double s = Double.parseDouble(args[0]);
double x = Double.parseDouble(args[1]);
double r = Double.parseDouble(args[2]);
double t = Double.parseDouble(args[3]);
double price = Double.parseDouble(args[4]);
double vol = getSigma(s, x, r, t, price, 0.0, 100000.0, 0.01);
if (vol == Double.NaN) {
System.out.println("Invalid parameters inserted - results in nonreal volatility");
}
else {
System.out.println("The volatility is " + 100*vol + " %");
}
}
}
This works for some (apparently small values of volatility), as for e.g. when given an input
> run BlackScholesBinary 30.14 15.0 0.01 0.25 15.178
The program returns "The volatility is 42.30907986831588 %"
But when I give an input
> run BlackScholesBinary 30.14 15.0 0.01 0.25 15.177, the program crashes.
Whats wrong with the code???