Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
943 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...