我是C的新手,我正在尝试寻找机器epsilon(1.0 + macheps> 1.0),eta(eta> 0.0)和MAX(MAX< infinity),但我的代码不起作用如预期。首先,使用80位精度计算macheps。如何强制它单,双和长双?其次,代码根本没有完成双精度计算结果。
编辑:修正了格式错误。
/* macheps eta max */
#include <stdio.h>
#include <math.h>
#include <float.h>
#define TYPE long double
int main(void)
{
TYPE macheps = (TYPE) 1.0;
TYPE eta = (TYPE) 1.0;
TYPE maksymilian = (TYPE) 2.0;
TYPE real_macheps;
TYPE real_eta;
TYPE real_maksymilian;
TYPE something = (TYPE) 1.0 + (TYPE) macheps;
while ((TYPE) something > (TYPE) 1.0)
{
real_macheps = (TYPE) macheps;
printf("%e ", (TYPE) real_macheps);
macheps = (TYPE) macheps/(TYPE) 2.0;
something = (TYPE) 1.0 + (TYPE) macheps;
}
printf("%e\n", (TYPE) real_macheps);
while ((TYPE) eta > (TYPE) 0.0)
{
real_eta = (TYPE) eta;
eta = (TYPE) eta/(TYPE) 2.0;
}
printf("%e\n", (TYPE) real_eta);
while ((TYPE) maksymilian != INFINITY)
{
(real_maksymilian) = (TYPE) maksymilian;
maksymilian = (TYPE) maksymilian*(TYPE) 2.0;
}
real_maksymilian = (TYPE) real_maksymilian * (TYPE) (2.0-(TYPE) real_macheps);
printf("%e\n", (TYPE) real_maksymilian);
}
EDIT2:上面的代码不应该强制精确吗?我错过了什么?
EDIT3:仍然没有为长双打给出正确的目标。
答案 0 :(得分:0)
long
是long signed int
的简写,因此是整数类型。请改用long double
。
根据无法呈现的数字的舍入方式,(1.0 + machepsfloat) > 1.0
可能始终为真。检查<float.h>
中的FLT_ROUNDS
以确定实施的舍入行为。
答案 1 :(得分:0)
您的程序将调用未定义的行为。在C中,long
表示long int
而非long double
。
答案 2 :(得分:0)
忘记发布更正的代码。我不得不做一个解决方案,但它有效:
/* macheps eta max */
#include <stdio.h>
#include <math.h>
#include <float.h>
#define TYPE long double /* printf 'e' for float and double, 'Le' for long double */
/* used_type: float 0, double 1, long double 2 */
int main(void)
{
int used_type = 2;
TYPE macheps = (TYPE) 1.0;
TYPE eta = (TYPE) 1.0;
TYPE maksymilian = (TYPE) 1.0;
TYPE real_macheps = 0.0;
TYPE real_eta = 0.0;
TYPE real_maksymilian = 0.0;
TYPE something = (TYPE) 1.0 + (TYPE) macheps;
while ((TYPE) something > (TYPE) 1.0)
{
real_macheps = (TYPE) macheps;
macheps = (TYPE) macheps/(TYPE) 2.0;
something = (TYPE) 1.0 + (TYPE) macheps;
}
while ((TYPE) eta > (TYPE) 0.0)
{
real_eta = (TYPE) eta;
eta = (TYPE) eta/(TYPE) 2.0;
}
while ((TYPE) maksymilian != INFINITY)
{
(real_maksymilian) = (TYPE) maksymilian;
maksymilian = (TYPE) maksymilian*(TYPE) 2.0;
}
real_maksymilian = (TYPE) real_maksymilian * (TYPE) (2.0-(TYPE) real_macheps);
if (used_type == 2)
{
printf("%Le\n", (TYPE) real_macheps);
printf("%Le\n", (TYPE) real_eta);
printf("%Le\n", (TYPE) real_maksymilian);
}
else
{
printf("%e\n", (TYPE) real_macheps);
printf("%e\n", (TYPE) real_eta);
printf("%e\n", (TYPE) real_maksymilian);
}
}