recursion – what is the initial value?


Category:
0
0

I thought plot x after def x=x[1]+1 will return as serial numbers starting from 1 .

To my surprise, I get 3 as the starting number. (Please see attached screenshot. What am I missing or doing wrong?

 

Thanks

Arun

Attachments:
Marked as spam
Posted by (Questions: 11, Answers: 16)
Asked on April 27, 2018 4:35 am
212 views
0
Private answer

Yeah, I can see how that would be very annoying. And for this one I am going to blame poor design on behalf of Thinkorswim developers. There is no way that should be happening. The only explanation for it is something called “prefetch”. Which should only be used by the platform when computing variables that require 2 or more bars to calculate the current value. Ok, maybe this fits that’s case.

But fortunately we have a method to handle this:

rec x = CompoundValue(1, x[1] + 1, 0);
plot test1 = x;

We use the method named CompoudValue() to set the initial value of the variable. You can read more about that method here: http://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Others/CompoundValue.html

Note: The use of rec in place of def in variable declaration has no impact on behavior. Either rec or def can be used. However to make the code more readable it’s best to use rec for declaring recursive variables. Also, it is not possible to plot a recursive variable directly, so we must always assign that as a separate plot statement.

Marked as spam
Posted by (Questions: 37, Answers: 4118)
Answered on April 27, 2018 7:38 am