我有一个问题,我的二进制搜索算法找到2的平方根似乎是在一个无限循环并永远运行:
num = 2
low = 1
high = num
i = 0
while((i**2) != 2): #was while(low<high): but wasnt working with it either
i = low + (high - low) / 2;
sqrt = i * i
if (sqrt == num):
print(i)
elif(sqrt < num):
low = i
else:
high = i
print(sqrt)
testRoot = 2 ** (.5)
print(testRoot)
Run Code Online (Sandbox Code Playgroud)
我不确定我的while循环是否存在问题.我认为这将是一个非常直接的二进制搜索算法,稍作修改以适应平方根方面.
在运行我的代码时,我似乎无法让它产生任何输出.我不确定代码或编译器是否存在真正的问题,因为我认为我的算法与我过去的算法非常接近.
I have read multiple articles regarding floating point variables comparison, but failed to understand and get the required knowledge from those articles. So, here I am posting this question.
What is the good way to compare two float variables? Below is the code snippet:
#define EPSILON_VALUE 0.0000000000000001
bool cmpf(float A, float B)
{
return (fabs(A - B) < EPSILON_VALUE);
}
int main()
{
float a = 1.012345679, b = 1.012345678;
if(cmpf(a, b))cout<<"same"<<endl;
else cout<<"different"<<endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
The output: same …
我有一个表单输入来获取一个数字(这是一个价格).它可以是像小数字102,5.我必须将它与例如102,6的其他小数进行比较.怎么办呢?我不想使用round()因为我可以完全比较.
都int和float在Java中都是32位的大小的值.是否可以编写一对函数
int toInt(float f);
float toFloat(int n);
Run Code Online (Sandbox Code Playgroud)
如果f1和f2是任意float 非NaN值,i1和i2是任意int值:
f1 < f2 当且仅当 toInt(f1) < toInt(f2)f1 > f2 当且仅当 toInt(f1) > toInt(f2)f1 == f2 当且仅当 toInt(f1) == toInt(f2)toInt(toFloat(i1) == i1toFloat(toInt(f1)) == f1编辑:我已经编辑了问题以排除浮动的NaN值,这要归功于解释这些问题的答案.
我想以#if预定义变量的浮点(或字符串)值为条件。
正如我所见,如果预定义变量的值是整数,则#if效果很好。但是,如果它是浮点数或字符串,则 if 无法按预期工作。
例如:
#define _VER_ = 103
#if _VER_ == 103
//Do somthing
#endif
Run Code Online (Sandbox Code Playgroud)
上面的代码按预期工作,#if根据_VER_值变为活动/不活动。但是,如果_VER_将该值设置为1.0.3或 则"1.0.3"不会#if按预期工作。
例如:
#define _VER_ = 1.0.3
#if _VER_ == 1.0.3
//Do somthing
#endif
Run Code Online (Sandbox Code Playgroud)
或这个:
#define _VER_ = "1.0.3"
#if _VER_ == "1.0.3"
//Do somthing
#endif
Run Code Online (Sandbox Code Playgroud)
两个代码示例均未按预期工作,无论值#if如何,它们都保持不活动状态_VER_。
如何使其正常工作?
public class yyy
{
public static void main(String[] args)
{
double sum = 0;
float d = 0;
while (d != 10.0) {
d += 0.1;
sum += sum + d;
}
System.out.print("The sum is: "+sum);
}
}
Run Code Online (Sandbox Code Playgroud)
d了double但没有改变.