简体   繁体   中英

avoiding negative values in C++

I have the following function, and I tried to avoid negative values by including the if statement, but it didn't help. ...suggestions on how I might fix this...

double G(double S, double X, double r, double div, double k, double T)
{
  double g=0;
  g=Phi(d1(S,X,r,div,k,T))/(exp(-div*T)*S*k*sqrt(T));
 if((isnan)(g) || (isinf)(g) || (g<0)) g=0;
  return g;
}

The value you are getting is not negative. 2.17691e-06 is the exponential representation for 2.17691 x 1/1000000 = 0.00000217691. Have a look at exponentiation .

if you don't want to show the exponentiation sign, consider setting the precision of the digit before showing/using g. One of the ways to set precision is here .

You have the right idea, but the syntax is a little bit off. Try this:

double G(double S, double X, double r, double div, double k, double T)
{
  double g=0;
  g=Phi(d1(S,X,r,div,k,T))/(exp(-div*T)*S*k*sqrt(T));
  if(isnan(g) || isinf(g) || (g<0)) g=0;
  return g;
}

Are you setting the value of a non-double type variable while calling this function? Are you getting any warnings? That should give you a clue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM