# Can we improve getPowerDeriv.m?

**URL:** <https://forum.dynare.org/t/can-we-improve-getpowerderiv-m/27528>\
**Category:** Perfect foresight simulations\
**Created:** [3 May 2025 00:47 UTC](https://forum.dynare.org/t/can-we-improve-getpowerderiv-m/27528 "2025-05-03T00:47:25Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![prometheu](https://forum.dynare.org/letter_avatar_proxy/v4/letter/p/258eb7/32.png) [@prometheu](https://forum.dynare.org/u/prometheu)\
**Post date:** [3 May 2025 00:47 UTC](https://forum.dynare.org/t/can-we-improve-getpowerderiv-m/27528/1 "2025-05-03T00:47:25Z")

</div>

I am running a loop of deterministic simulation using perfect\_foresight\_solver.m. The total running time is about 6 hours, and the profiler tells me that a single funcion getPowerDeriv.m uses about half of the total time. This function calculates the k-order derivative of x^p. It uses a series of “if” conditions and a “for loop”. I wonder if we can improve it. I attach the function below.

function dxp=getPowerDeriv(x,p,k)  
if (abs(x) \< 1e-12) && (p \> 0) && (k \> p) && (abs(p - round(p)) \< 1e-12)  
dxp = 0;  
else  
dxp = x^(p-k);  
for i=0:k-1  
dxp = dxp\*p;  
p = p-1;  
end  
end  
end

---

<div class="post-metadata">

**Author:** ![jpfeifer](https://forum.dynare.org/user_avatar/forum.dynare.org/jpfeifer/32/5044_2.png) [@jpfeifer](https://forum.dynare.org/u/jpfeifer)\
**Post date:** [4 May 2025 14:32 UTC](https://forum.dynare.org/t/can-we-improve-getpowerderiv-m/27528/2 "2025-05-04T14:32:01Z")

</div>

Can you maybe provide me with the file, potentially via PM. We may revisit [rewrite getPowerDeriv assignments in temporary terms (#240) · Issues · Dynare / dynare · GitLab](https://git.dynare.org/Dynare/dynare/-/issues/240)
