找回密码
 欢迎注册
查看: 11486|回复: 7

[提问] 写一个类似于LinearRecurrence的函数

[复制链接]
发表于 2013-2-20 12:24:08 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?欢迎注册

×
功能类似于Mathematica的LinearRecurrence,
f(init, n)最后一个参数是生成序列的长度(包含初始值),除了最后一个参数前面的是不定参数,表示初始值,
如:
f(1,1, 10)-->1, 1, 2, 3, 5, 8, 13, 21, 34, 55
f(2,3,4, 10)-->2, 3, 4, 9, 16, 29, 54, 99, 182, 335
f[x, y, z,  6]--> x, y, z, x + y + z, x + 2 y + 2 z, 2 x + 3 y + 4 z
毋因群疑而阻独见  毋任己意而废人言
毋私小惠而伤大体  毋借公论以快私情
发表于 2013-2-20 12:36:08 | 显示全部楼层
循环呗,这个简单
毋因群疑而阻独见  毋任己意而废人言
毋私小惠而伤大体  毋借公论以快私情
发表于 2013-2-20 15:24:27 | 显示全部楼层
1# chyanog
这个,最好是这种格式:
f({x1,x2,x3,...},n)  ------>  {x1,x2,x3,......}
毋因群疑而阻独见  毋任己意而废人言
毋私小惠而伤大体  毋借公论以快私情
 楼主| 发表于 2013-2-20 17:47:46 | 显示全部楼层
3# wayne
这个可以随意,就是不太清楚C/C++能否也能这样写
毋因群疑而阻独见  毋任己意而废人言
毋私小惠而伤大体  毋借公论以快私情
发表于 2013-2-20 21:26:41 | 显示全部楼层
可以的,传入数组即可 ,例如:
void f(int arr[],int n)
==============================
如果初始数列有c个,那么,存在递推公式:
a[n]=2*a[n-1]-a[n-c]

试着写了个C程序:

  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. int main(int c,char** v)
  4. {
  5.     if(c>2)
  6.     {
  7.         int len=atoi(v[c-1]);
  8.         if(len<c-2) return ;
  9.         int tmp[c-1], arr[len],i;
  10.         arr[c-2]=0;
  11.         for(i=0; i<c-2; ++i)
  12.         {
  13.             tmp[i]=atoi(v[i+1]);
  14.             arr[i]=tmp[i];
  15.             arr[c-2]+=arr[i];
  16.         }
  17.         while(++i<len) arr[i]=2*arr[i-1]-arr[i-c+1];
  18.         for(i=0; i<len; ++i) printf("%d\t",arr[i]);
  19.     }
  20. }
复制代码
==============================================
C:\Users\yoyo\Desktop>a.exe 1 3 6 20
1       3       6       10      19      35      64      118     217     399     734     1350    2483    4567    8400    15450   28417   52267   96134   176818
C:\Users\yoyo\Desktop>a 1 1 10
1       1       2       3       5       8       13      21      34      55
毋因群疑而阻独见  毋任己意而废人言
毋私小惠而伤大体  毋借公论以快私情
 楼主| 发表于 2013-2-21 16:57:18 | 显示全部楼层
5# wayne
这个关系式不错,我都没有发现呢
毋因群疑而阻独见  毋任己意而废人言
毋私小惠而伤大体  毋借公论以快私情
 楼主| 发表于 2013-2-21 17:00:20 | 显示全部楼层
本帖最后由 chyanog 于 2013-2-21 17:27 编辑

  1. f1[init_, n_] :=
  2. Nest[Join[#, {2 #[[-1]] - #[[-Length@init - 1]]}] &, #~Join~{Tr@#} &@init, n - Length@init]

  3. f2[init_, n_] :=
  4. Nest[Join[#, {Tr@#[[-Length@init ;;]]}] &, init, n + 1 - Length@init]
复制代码
写了两个Mathematica的版本,
毋因群疑而阻独见  毋任己意而废人言
毋私小惠而伤大体  毋借公论以快私情
发表于 2013-2-21 19:43:39 | 显示全部楼层
let fb l n = map (\(_, x) -> x) \$ take n (iterate (\(l, _)->((tail l)++[sum l], (head l))) (l, head l))

fb [1,1,1] 10
[1,1,1,1,3,5,9,17,31,57]

评分

参与人数 1鲜花 +2 收起 理由
wayne + 2 haskell代码可读性很差哟~~:)

查看全部评分

毋因群疑而阻独见  毋任己意而废人言
毋私小惠而伤大体  毋借公论以快私情
您需要登录后才可以回帖 登录 | 欢迎注册

本版积分规则

小黑屋|手机版|数学研发网 ( 苏ICP备07505100号 )

GMT+8, 2024-4-28 12:12 , Processed in 0.047241 second(s), 17 queries .

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表