请帮帮我!
有operation[f_]
程序。
它正常工作并绘制功能:Cos,Sin。但是,不幸的是,它不适用于E ^ x和Log [E,x]并输出错误,可能是因为输入了不正确的函数名称或其他东西;((有什么问题?
spxsin = {-1, -0.35, 0.3, 0.95, 1.6, 2.375, 3.15, 3.925, 4.7, 5.025,
5.35, 5.675, 6};
spxcos = {-1, -0.75, -0.5, -0.25, 0, 0.775, 1.55, 2.325, 3.1, 3.825,
4.55, 5.275, 6};
spxlny = {-1, 0.75, 2.5, 4.25, 6};
spxey = {-1, 0.75, 2.5, 4.25, 6};
operation[f_] := Block[{data},
data = Table[{x, f[x]}, {x, -1, 6, 0.1}];
Graphics[{Thick, Blue, Line[data],
Green, Table[Point[{spx[[i]], f[spx[[i]]]}], {i, 1, Length[spx]}],
Pink, Opacity[.7],
Table[Rectangle[{spx[[i]], f[spx[[i]]]}, {spx[[i + 1]],
f[spx[[i + 1]]]}], {i, 1, Length[spx] - 1}]
}, Axes -> True]]
Which[ f == Sin, spx := spxsin, f == Cos, spx := spxcos, f == E^x ,
spx := spxlny, f == Log, spx := spxey]
operation[Sin]
operation[Cos]
operation[E^x]
operation[Log]
答案 0 :(得分:2)
编辑现已测试:您可以将纯函数传递给operation
,而不是:operation[E^x]
尝试
operation[E^# &]
或者例如,如果你想要一个基础2日志,它将是
operation[Log[2,#]&]
要指出的其他一些事项:Log
因为x
表范围为负而失败。
此外,您拥有的Which
声明没有做任何事情。由于不在函数中,f
未定义,因此所有条件都不是True
。在函数内移动Which
,这有效:
spxsin = {-1, -0.35, 0.3, 0.95, 1.6, 2.375, 3.15, 3.925, 4.7, 5.025,
5.35, 5.675, 6};
spxcos = {-1, -0.75, -0.5, -0.25, 0, 0.775, 1.55, 2.325, 3.1, 3.825,
4.55, 5.275, 6};
spxlny = {-1, 0.75, 2.5, 4.25, 6};
spxey = {-1, 0.75, 2.5, 4.25, 6};
operation[f_] :=
Block[{data}, data = Table[{x, f[x]}, {x, -1, 6, 0.1}];
Clear[spx];
Which[
TrueQ[f == Sin], spx := spxsin,
TrueQ[f == Cos], spx := spxcos ,
TrueQ[f == (E^# &)], spx := spxey ];
Graphics[{Thick, Blue, Line[data], Green,
Table[{PointSize[.1], Point[{spx[[i]], f[spx[[i]]]}]}, {i, 1, Length[spx]}],
Pink, Opacity[.7],
Table[Rectangle[{spx[[i]], f[spx[[i]]]}, {spx[[i + 1]],
f[spx[[i + 1]]]}], {i, 1, Length[spx] - 1}]}, Axes -> True,
AspectRatio -> 1/GoldenRatio]]
请注意每个测试都包含在TrueQ
中,以确保它是True
或False
(所有值的测试Sin==Cos
都不为false,因此不返回False
)
operation[Sin]
operation[Cos]
operation[E^# &]
现在,如果您希望Exp
也能正常工作,则需要在Which
语句中明确地放置该表单。 (f==(E^#&) || f==Exp
)
答案 1 :(得分:1)
Euler的E需要输入为Esc ee Esc。 在你看来,你输入的是标准的E。
另请注意,Exp是Mathematica中的指数函数。