ch05 exercises
This commit is contained in:
30
exercises/ch05/ex5_4.lua
Normal file
30
exercises/ch05/ex5_4.lua
Normal file
@@ -0,0 +1,30 @@
|
||||
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)
|
||||
Reference in New Issue
Block a user