Module:SB tree: Difference between revisions
No edit summary |
Added comments to code |
||
| Line 2: | Line 2: | ||
local rat = require('Module:Rational') | local rat = require('Module:Rational') | ||
-- Function that constructs a Stern-Brocot tree, | -- Function that constructs a sequence of ratios according to the Stern-Brocot tree | ||
-- Ratios are entered as arrays, such as {1, 1} for the ratio 1/1 and {1, 0} for the ratio 1/0 | |||
-- Mediants are found between each ratio iteratively | |||
-- Start and stop ratio may be any two ratios, but the default values are 1/1 and 1/0 | |||
-- Depth may be specified to be any value, but the default is 4 | |||
-- Edge extend recursively finds the mediants of the first two and last two ratios; default is 0 | |||
-- Transpiled from python to lua with aid of ChatGPT; may need testing to make sure code works | -- Transpiled from python to lua with aid of ChatGPT; may need testing to make sure code works | ||
function p.sb_tree(depth, start_ratio, stop_ratio, edge_extend) | function p.sb_tree(depth, start_ratio, stop_ratio, edge_extend) | ||
-- Default parameter values | |||
depth = depth or 4 | |||
start_ratio = start_ratio or {1, 1} | |||
stop_ratio = stop_ratio or {1, 0} | |||
edge_extend = edge_extend or 0 | |||
-- Initial tree are the ratios 1/1 and 1/0 | -- Initial tree are the ratios 1/1 and 1/0 | ||
local tree = {start_ratio, stop_ratio} | local tree = {start_ratio, stop_ratio} | ||
| Line 26: | Line 37: | ||
end | end | ||
for i = 1, edge_extend do | |||
for i = 1, | |||
local last_ratio_1 = tree[#tree - 1] -- Second last ratio | local last_ratio_1 = tree[#tree - 1] -- Second last ratio | ||
local last_ratio_2 = tree[#tree] -- Last ratio | local last_ratio_2 = tree[#tree] -- Last ratio | ||
| Line 44: | Line 54: | ||
end | end | ||
-- Test function that produces the SB tree as a one-column table | -- Test function that produces the ratios of the SB tree as a one-column table, using default parameters | ||
-- To try this out, add the following text (not as a lua comment): | |||
-- {{#invoke:SB_tree|sb_table}} | |||
function p.sb_table(frame) | function p.sb_table(frame) | ||
result = '{| class="wikitable"\n' | result = '{| class="wikitable"\n' | ||