31 lines
634 B
Lua
31 lines
634 B
Lua
local function polynomial(coefs, x)
|
|
local sum = 0
|
|
for i = 1, #coefs do
|
|
sum = sum + coefs[i] * x^i
|
|
end
|
|
|
|
return sum
|
|
end
|
|
|
|
local function table_str(t)
|
|
local str = "{ "
|
|
for _, v in pairs(t) do
|
|
str = str + v + ", "
|
|
end
|
|
|
|
str = str + "}"
|
|
end
|
|
|
|
local function test(coefs, x, should_be)
|
|
local res = polynomial(coefs, x)
|
|
if res ~= should_be then
|
|
print(
|
|
("Test failed. Should have been %f, was %f. coefs: %s, x: %f"):format(should_be, res, table_str(coefs), x)
|
|
)
|
|
else
|
|
print("Test passed.")
|
|
end
|
|
end
|
|
|
|
test({1, 2, 3}, 2, 1 * 2^1 + 2 * 2^2 + 3 * 2^3)
|