ex5_4.lua 634 B

123456789101112131415161718192021222324252627282930
  1. local function polynomial(coefs, x)
  2. local sum = 0
  3. for i = 1, #coefs do
  4. sum = sum + coefs[i] * x^i
  5. end
  6. return sum
  7. end
  8. local function table_str(t)
  9. local str = "{ "
  10. for _, v in pairs(t) do
  11. str = str + v + ", "
  12. end
  13. str = str + "}"
  14. end
  15. local function test(coefs, x, should_be)
  16. local res = polynomial(coefs, x)
  17. if res ~= should_be then
  18. print(
  19. ("Test failed. Should have been %f, was %f. coefs: %s, x: %f"):format(should_be, res, table_str(coefs), x)
  20. )
  21. else
  22. print("Test passed.")
  23. end
  24. end
  25. test({1, 2, 3}, 2, 1 * 2^1 + 2 * 2^2 + 3 * 2^3)