本文介绍了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]]]
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,提高循环附加的速度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!