| 123456789101112131415161718192021222324252627282930 |
- 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)
|