Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
945 views
in Technique[技术] by (71.8m points)

c - If Statement when x is near a value

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...