gpt4 book ai didi

java - 在计算之前查找未知的 "correct"值

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:38:41 28 4
gpt4 key购买 nike

问题如下,我有一个很大或很小的数字(可以是其中之一),我需要调整这个数字并通过计算来计算它。给定计算结果,它至少要在小数点后 5 位达到一定值。

所以我需要创建一个方法来接受这个起始值,尝试根据当前结果增加或减少它,直到我得到正确的结果。我做了一些尝试,但没有成功。

这是一个根本不起作用的例子,但它暗示了我的意思......(这只是一个小规模的测试用例)

   public class Test {
public static void main(String[]args)
{
double ran = 100 + (int)(Math.random() * 100000.999999999);
int count = 0;
double tmpPay = 3666.545;
double top = tmpPay;
double low = 0;

while ( tmpPay != ran )
{
if ( tmpPay > ran)
{
if( low == 0)
{
tmpPay = top / 2;
top = tmpPay;
}
else
{
tmpPay = tmpPay + ((top - low) / 2);
top = tmpPay;
}
}

if (tmpPay < ran)
{
tmpPay = top * 1.5;
low = top;
top = tmpPay;
}
}
System.out.println(" VAlue of RAN: " +ran + "----VALUE OF tmpPay: " + tmpPay + "---------- COUNTER: " + count);
}

示例 2 可能是一个更清晰的描述。这是我现在的解决方案..

guessingValue = firstImput;

while (amortization > tmpPV)
{
guessingValue -= (decimal)1;
//guessingVlue -- > blackbox
amortization = blackboxResults;
}
while (amortization < tmpPV)
{
guessingValue += (decimal)0.00001;
//guessingVlue -- > blackbox
amortization = blackboxResults;
}

最佳答案

正如我在上面的评论中提到的,您不应该使用内置运算符比较 double 。这是您的代码无法正常工作的主要原因。第二个是在 else 子句中 tmpPay = tmpPay + ((top-low)/2);而不是 tmpPay = tmpPay - ((top-low)/2 );

完整的固定代码如下:

public class Test {
private static final double EPSILON = 0.00001;
public static boolean isEqual( double a, double b){

return (Math.abs(a - b) < EPSILON);

}


public static void main(String[]args)
{

double ran = 100 + (int)(Math.random() * 100000.999999999);
int count = 0;
double tmpPay = 3666.545;
double top = tmpPay;
double low = 0;

while ( !isEqual(tmpPay, ran))
{
if ( tmpPay > ran)
{
if( isEqual(low, 0.0))
{
tmpPay = top / 2;
top = tmpPay;
}
else
{
tmpPay = tmpPay - ((top - low) / 2);
top = tmpPay;
}
}

if (tmpPay < ran)
{
tmpPay = top * 1.5;
low = top;
top = tmpPay;
}
System.out.println("RAN:"+ran+" tmpPay:"+tmpPay+" top:"+top+" low:"+low+" counter:"+count);
count++;
}
System.out.println(" VAlue of RAN: " +ran + "----VALUE OF tmpPay: " + tmpPay + "---------- COUNTER: " + count);




}
}

关于java - 在计算之前查找未知的 "correct"值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19658162/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com