我已经问过一个早先的问题,关于如何根据问题的要求设置我的功能,并且已经使用了我编写的代码,现在的问题是,无论如何,输出保持不变,无论如何我在k
中更改了参数first-value-k-or-higher x tol 1
的值。
以下是基于我在其他问题中的反馈的代码:
(define (square x)
(* x x))
(define (first-value-k-or-higher x tol k)
(if (<= (abs(- x
(square (babylonian x k))))
tol)
k
(first-value-k-or-higher x tol (+ k 1))))
(define (terms-needed x tol)
(first-value-k-or-higher x tol 1))
如果函数看起来像我上面的那个,那么这里有几个示例输出:
> (terms-needed 15 .001)
1
> (terms-needed 234 3)
1
> (terms-needed 23421 453)
1
>
如果我将函数terms-needed x tol
更改为这样的:
(define (square x)
(* x x))
(define (first-value-k-or-higher x tol k)
(if (<= (abs(- x
(square (babylonian x k))))
tol)
k
(first-value-k-or-higher x tol (+ k 1))))
(define (terms-needed x tol)
(first-value-k-or-higher x tol 100))
新功能将输出:
> (terms-needed 15 .0001)
100
> (terms-needed 243 3)
100
>
Terms-needed
应该评估在tol
内所需的无限和中的项数,即最小的k
,使得x
和(square (babylonian x k))
之间的差异小于tol
。正如我所提到的,问题是我不断得到“1”的相同输出,无论我为terms-needed x tol
的参数值放下什么。我也相信这是问题的来源,因为如果我将(first-value-k-or-higher x tol 1))
更改为像(first-value-k-or-higher x tol 2))
或任何其他值,(first-value-k-or-higher x tol 2))
将输出该值,例如使用(first-value-k-or-higher x tol 2))
将输出2。
这是运行babylonian x k
所需的程序first-value-k-or-higher x tol k
所需的函数terms-needed x tol
:
(define (babylonian x k)
(if (>= x 1)
(if (= k 0)
(/ x 2)
(* (/ 1 2) (+ (expt x (/ 1 2)) (/ x (expt x (/ 1 2))))))
1)
)
babylonian
函数应该使用巴比伦方法计算根,并评估第k个近似值(Sk)。 babylonian
函数也通过了所有测试。
这里是my earlier problem获取更多背景信息
没有,
(define (babylonian x k)
(if (>= x 1)
(if (= k 0)
(/ x 2)
(* (/ 1 2) (+ (expt x (/ 1 2)) (/ x (expt x (/ 1 2))))))
1)
)
不可能计算x
的“k ^ th approximation”,因为在内部k
表达式的替代中没有if
。