Mathematica:将参数的默认值设置为非恒定值吗? [英] Mathematica: set default value for argument to nonconstant?

查看:79
本文介绍了Mathematica:将参数的默认值设置为非恒定值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以将函数参数的默认值设置为不是恒定的
吗?例如:

Can I set the default value for a function argument to be something that's not constant? Example:

tod := Mod[AbsoluteTime[], 86400] 
f[x_:tod] := x    

在上面, tod在每次评估时都会更改,但是 f []确实会b $ b不是。 ?f收益率:

In the above, 'tod' changes every time I evaluate it, but "f[]" does not. "?f" yields:

f[x_:42054.435657`11.376386798562935] := x 

显示创建该函数时默认值是硬编码的。

showing the default value was hardcoded when I created the function.

这里有解决方法吗?

推荐答案

如果函数保留其参数,这似乎可以工作:

It seems to work if the function holds its arguments:

tod := Mod[AbsoluteTime[], 86400]
SetAttributes[f, HoldAll];
f[x_: tod] := x

In [23]:= f []

In[23]:= f[]

Out [23] = 47628.994048

Out[23]= 47628.994048

In [24]:= f []

In[24]:= f[]

Out [24] = 47629.048193

Out[24]= 47629.048193

或者您可以使用以下结构代替默认值:

Or you can use a construction like the following instead of a default value:

g[] := g[Mod[AbsoluteTime[], 86400]]
g[x_] := x

输入[27]:= g []

In[27]:= g[]

输出[27] = 47706.496195

Out[27]= 47706.496195

In [28]:= g []

In[28]:= g[]

Out [28] = 47707.842012

Out[28]= 47707.842012

这篇关于Mathematica:将参数的默认值设置为非恒定值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆