Mathematica,提高循环附加的速度 [英] Mathematica, improve speed for appendto in the loop

查看:106
本文介绍了Mathematica,提高循环附加的速度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何改善以下功能?目前速度很慢.预先感谢.

how to improve the following function? currently it is very slow. Thanks in advance.

    discounts[firstDFF_] :=
        Module[ 
            {len = Length[swapdata], running = firstDF, newdisc, disclist = {firstDFF}, k = 2},

            Do[
                newdisc = (1 - swapdata[[k]]*running)/(1 + swapdata[[k]]);

                running += newdisc;

                AppendTo[disclist, newdisc]
                , 
                {k, 1, len}
            ];

            disclist
        ];

它是用于在引导过程中获取折扣因子的列表.

it is for getting a list of discount factor during the bootstrapping.

推荐答案

只需将disclist = {disclist, newdisc}Flatten而不是AppendTo[disclist, newdisc]一起使用,即可将代码从14.59秒加速到0.34秒.

The code was sped up from 14.59 seconds to 0.34 seconds simply by using disclist = {disclist, newdisc} with Flatten instead of AppendTo[disclist, newdisc].

下面的演示.首先是OP的原始代码.

Demonstration below. First the OP's original code.

swapdata = ConstantArray[0.03, 100000];

firstDF = 1;

discounts[firstDFF_] := Module[{len = Length[swapdata],
    running = firstDF,
    newdisc,
    disclist = {firstDFF}, k = 2},
   Do[newdisc = (1 - swapdata[[k]]*running)/(1 + swapdata[[k]]);
    running += newdisc;
    AppendTo[disclist, newdisc], {k, 1, len}];
   disclist];

First[{time, result1} = Timing[discounts[100]]]

14.594

14.594

discounts[firstDFF_] := Module[{
    len = Length[swapdata],
    running = firstDF,
    newdisc,
    disclist = {firstDFF}, k = 2},
   Do[newdisc = (1 - swapdata[[k]]*running)/(1 + swapdata[[k]]);
    running += newdisc;
    disclist = {disclist, newdisc}, {k, 1, len}];
   Flatten@disclist];

First[{time, result2} = Timing[discounts[100]]]

0.343

0.343

result1 == result2

这篇关于Mathematica,提高循环附加的速度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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