0

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;
}
4
  • 1
    What are you saying? The function G still returns negative values in some situations? Commented Oct 17, 2011 at 4:40
  • yes indeed, it is returning values like 2.17691e-06 in scenarios where it should be returning 0 Commented Oct 17, 2011 at 4:53
  • 8
    2.17691e-06 is not a negative number. It is the same as 0.00000217691 Commented Oct 17, 2011 at 4:59
  • 2
    @itcplpl: That value isn't negative. Understand that floating points are "lossy": they only use a finite amount of memory, so the answer won't be exact. That 2.176891e-06 is really close to 0, and your program should probably consider it "essentially zero". Commented Oct 17, 2011 at 5:01

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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;
}

2 Comments

changed it, but I still get the same negative values.
Can you please post some sample input and output?
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.