1

I am trying to solve the numerical equation:

sin^2(x)tan(x) = 0.499999

Using a while loop in C. However I was only able to get program to print an answer if I rounded to 0.5. This led me to thinking, is there a way of writing:

For(x=0;x<=360;x=x+0.001)
{ y=f(x)
If(y **is near x**(e.g. Within 1 percent) )
Do something etc.
}

Is there a way of telling the computer to execute a task if the value is sufficiently near. Such as in this if statement? Thank you.

mlp
  • 809
  • 7
  • 21
user138774
  • 23
  • 2

2 Answers2

4

Use a relative difference, such as:

#include <math.h>

static inline double reldiff(double x, double y)
{
    return fabs(x - y) / fmax(fabs(x), fabs(y));
}

Now your test becomes:

if (reldiff(x, y) < 0.01)   // 1% as requested
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
0

Well, a simple solution would be.

if (y >= x-x/100 && y <= x+x/100)
{
   [execute code...]
}

Essentially what it does is check if y is between [x minus 1% of x] and [x plus 1% of x]. Should work alright.

stelioslogothetis
  • 9,371
  • 3
  • 28
  • 53