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

问题描述

如何改进以下功能?目前它非常缓慢.提前致谢.

 折扣[firstDFF_] :=模块[{len = 长度 [swapdata], running = firstDF, newdisc, disclist = {firstDFF}, k = 2},做[newdisc = (1 - 交换数据[[k]]*运行)/(1 + 交换数据[[k]]);运行 += 新光盘;追加到[光盘列表,新光盘],{k, 1, 长度}];唱片];

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

解决方案

通过使用 disclist = {disclist, newdisc}Flatten,代码从 14.59 秒加速到 0.34 秒 而不是 AppendTo[disclist, newdisc].

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

swapdata = ConstantArray[0.03, 100000];第一个DF = 1;折扣[firstDFF_] := 模块 [{len = 长度 [swapdata],运行 = firstDF,新盘,disclist = {firstDFF},k = 2},Do[newdisc = (1 - swapdata[[k]]*running)/(1 + swapdata[[k]]);运行 += 新光盘;AppendTo[disclist, newdisc], {k, 1, len}];唱片];首先[{time, result1} = 时间[折扣[100]]]

14.594

折扣[firstDFF_] := Module[{len = 长度 [swapdata],运行 = firstDF,新盘,disclist = {firstDFF},k = 2},Do[newdisc = (1 - swapdata[[k]]*running)/(1 + swapdata[[k]]);运行 += 新光盘;disclist = {disclist, newdisc}, {k, 1, len}];扁平化@disclist];首先[{time, result2} = 时间[折扣[100]]]

0.343

result1 == result2

是的

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.

解决方案

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].

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]]]
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]]]
result1 == result2

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

05-20 01:35