gpt4 book ai didi

algorithm - 三元搜索递归不正确

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:53:46 25 4
gpt4 key购买 nike

我从维基百科了解了三元搜索。我不确定参数绝对精度是什么意思。他们没有详细说明。但这是伪代码:

def ternarySearch(f, left, right, absolutePrecision):
#left and right are the current bounds; the maximum is between them
if (right - left) < absolutePrecision:
return (left + right)/2

leftThird = (2*left + right)/3
rightThird = (left + 2*right)/3

if f(leftThird) < f(rightThird):
return ternarySearch(f, leftThird, right, absolutePrecision)

return ternarySearch(f, left, rightThird, absolutePrecision)

我想从单峰函数中找到最大值。这意味着我想打印递增和递减序列的边界点。如果序列是

1 2 3 4 5 -1 -2 -3 -4

然后我想打印 5 作为输出。

这是我的尝试。它没有给出输出。你能帮忙或给我一个链接,其中包含关于自学三元搜索的好教程吗?

#include<iostream>

using namespace std;
int ternary_search(int[], int, int, int);
int precval = 1;

int main()
{
int n, arr[100], target;
cout << "\t\t\tTernary Search\n\n" << endl;
//cout << "This program will find max element in an unidomal array." << endl;
cout << "How many integers: ";
cin >> n;
for (int i=0; i<n; i++)
cin >> arr[i];
cout << endl << "The max number in the array is: ";
int res = ternary_search(arr,0,n-1,precval)+0;
cout << res << endl;
return 0;
}

int ternary_search(int arr[], int left, int right, int precval)
{
if (right-left <= precval)
return (arr[right] > arr[left]) ? arr[right] : arr[left];
int first_third = (left * 2 + right) / 3;
int last_third = (left + right * 2) / 3;
if(arr[first_third] < arr[last_third])
return ternary_search(arr, first_third, right, precval);
else
return ternary_search(arr, left, last_third, precval);
}

提前谢谢你。

最佳答案

绝对精度是指返回结果与真实结果之间的最大误差即max | returned_result - true_result | .在这种情况下,f是连续函数。

由于您正在查看一个离散函数,所以您最好做到 right - left <= 1 .然后,只需比较两个结果值并返回对应于较大值的值(因为您正在寻找 max )。

编辑

第一个分割点,数学上是2/3*left + right/3 , 应离散化为 ceil(2/3*left + right/3) (这样关系就是left < first_third <= last_third < right

所以 first_third = (left*2+right)/3应该改为first_third = (left*2 + right + 2)/3 .

关于algorithm - 三元搜索递归不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4282063/

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