gpt4 book ai didi

Octave 调用一个函数作为另一个函数的变量

转载 作者:行者123 更新时间:2023-12-05 01:01:27 24 4
gpt4 key购买 nike

我在 Octave 中编写了一个二分法,但它不能使用另一个函数..

我的二分法代码是这样的:

function[x,b] = bisection(f,a,b)

t = 10e-8

while abs(b-a) > t;
c = (a+b)/2;

if f(a) * f(b) <= 0
a = a;
b = c;
else
b = b;
a = c
endif
endwhile

x = (a+b)/2
endfunction

我已经有一个文件 f1.m:

function y = f1(x)
y = x^2 - 4;
endfunction

但是当我调用 [x,v] = bisection[f1,0,5] 时,我得到:

>> [t,v] = bisection(f1,0,5)
error: 'x' undefined near line 2 column 5
error: called from
f1 at line 2 column 3
error: evaluating argument list element number 1

最佳答案

您想要的是将指向 f1 的指针传递给您的函数 bisection 以便正确调用

[t,v] = bisection(@f1,0,5)

哪个输出:

t =    1.0000e-07
a = 0.62500
a = 0.93750
a = 1.0938
a = 1.1719
a = 1.2109
a = 1.2305
a = 1.2402
a = 1.2451
a = 1.2476
a = 1.2488
a = 1.2494
a = 1.2497
a = 1.2498
a = 1.2499
a = 1.2500
a = 1.2500
a = 1.2500
a = 1.2500
a = 1.2500
a = 1.2500
a = 1.2500
a = 1.2500
a = 1.2500
a = 1.2500
x = 1.2500
t = 1.2500
v = 1.2500

关于Octave 调用一个函数作为另一个函数的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44347283/

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