Mathematica 中是否有类似广义 Piecewise 的东西? [英] Is there something like generalized Piecewise in Mathematica?

查看:38
本文介绍了Mathematica 中是否有类似广义 Piecewise 的东西?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将三次样条定义为 Mathematica 8 中的函数,因为我有每个 P_{i}(当然,它们是多项式度 3) 对于每个区间 [x_{i}, x_{i + 1}], i = 0, ..., n.我想要做的是将区间 [x_{0}, x_{n + 1}] 中的 s 定义为 s(x)= P_{i}(x) 如果 x 在 [x_{i}, x_{i+1}] 中.随着 n 的变化,我该怎么做?我在考虑 Piecewise 但这没有用.

I'm trying to define a cubic spline as a function in Mathematica 8 as I've got every P_{i} (which, of course, are polynomials of degree 3) for each interval [x_{i}, x_{i + 1}], i = 0, ..., n. What I want to do is to define s in the interval [x_{0}, x_{n + 1}] as s(x) = P_{i}(x) if x is in [x_{i}, x_{i+1}]. How can I do that as n varies? I was thinking of Piecewise but that didn't work.

推荐答案

如果我没记错的话,这完全符合您的要求.不过还是有点丑.有更好的选择.

This does precisely what you ask, if I'm not mistaken. It's a bit ugly though. There are better alternatives.

n = 5;
ClearAll[f];
f[x_] = Piecewise[Table[{x^k, (k - 1)/n < x <= k/n}, {k, 0, n}]]

f[1/2]

(* ==> 1/8 *)

如果你想让结果依赖于全局变量 n(我不提倡)的当前状态,你可以替换 Set (=) 在带有 SetDelayed (:=) 的 f 的定义中,但这意味着为 f 的每次调用重新评估 Table.对于 n 的小值来说还不错,但我不喜欢它.这种情况下的结果如下所示:

If you want to make the result dependent on the current state of the global variable n (which I wouldn't advocate) thne you can replace the Set (=) in the definition of f with SetDelayed (:=), but this implies re-evaluating the Table for every call of f. Not that bad for small values of n, but I don't like it. Results in that case look like this:

n = 2; f[1/2]
n = 5; f[1/2]

(* ==>  1/2 

   ==>  1/8
*)

这篇关于Mathematica 中是否有类似广义 Piecewise 的东西?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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