TL; DR, the function declaration should be
\pgfmathdeclarefunction{manual_sum}{1}{% \pgfmathfloattoint{#1}\let\cnt\pgfmathresult% \pgfmathsetmacro\ret{0}% \foreach\i in{1,...,\cnt}{% \pgfmathsetmacro\ret{\ret+\i} % summing integer itself %\pgfmathsetmacro\ret{\ret+square(\i)} % general case \xdef\ret{\ret}% }% \pgfmathparse{\ret}% }
There are two problems in your code:
- First,
\foreach
introduces nested grouping and\ret
is trapped in the group. - Second, since pgfplots activates FPU, the
\pgfmathtruncatemacro\cnt{#1}
will make\cnt
be1
.- (This is in fact the flag of
#1
in the FPU representation.) - (flag
1
stands for positive number.)
- (This is in fact the flag of
To come over the first obstacle, I usually use \xdef
to smuggle the value. It is also worth noting that pgfplots introduces \pgfplotsforeachungrouped
, which is literally an ungrouped version of \foreach
.
For the second obstacle, one needs to check the manual carefully and finds that \pgfmathfloattoint{#1}\let\cnt\pgfmathresult
is the correct way to do the job.
this will bring you a curve that is different from the explicit_sum
, and then you will realize that #1*(#1-1)/2
is not the correct formula.