Lua - 數學庫:初學者指南

Hello, future programmers! Today, we're going to embark on an exciting journey into the world of Lua's Math Library. Don't worry if you've never written a line of code before – I'll be your friendly guide, and we'll explore this together step by step.

Lua - Math Library

介紹 Lua 的數學庫

Before we dive into the specifics, let's talk about what a math library is. Think of it as a toolbox filled with powerful mathematical tools that you can use in your programs. Just like you wouldn't build a house without a hammer and nails, you often can't write certain programs without these mathematical functions.

To use the math library in Lua, we start our program with:

math = require("math")

This line tells Lua, "Hey, I want to use the math toolbox in my program!"

Now, let's explore what's inside this toolbox.

三角函數

基础:正弦、餘弦和正切

Remember those tricky sine, cosine, and tangent functions from math class? Well, they're here in Lua, and they're actually pretty easy to use!

angle = math.pi / 4  -- This is 45 degrees in radians

print(math.sin(angle))  -- Outputs: 0.70710678118655
print(math.cos(angle))  -- Outputs: 0.70710678118655
print(math.tan(angle))  -- Outputs: 1.0

In this example, we're calculating the sine, cosine, and tangent of a 45-degree angle (π/4 radians). Notice how we use math.pi to represent π? That's another handy tool in our math library!

反三角函數

Lua also provides the inverse of these functions:

value = 1

print(math.asin(value))  -- Outputs: 1.5707963267949 (π/2 radians or 90 degrees)
print(math.acos(value))  -- Outputs: 0
print(math.atan(value))  -- Outputs: 0.78539816339745 (π/4 radians or 45 degrees)

These functions do the opposite of sin, cos, and tan. They take a value and return the angle (in radians) that would produce that value.

其他常見數學函數

幂和平方根

Need to calculate powers or square roots? Lua's got you covered!

base = 2
exponent = 3

print(math.pow(base, exponent))  -- Outputs: 8 (2^3)
print(math.sqrt(16))  -- Outputs: 4

math.pow(base, exponent) raises base to the power of exponent. math.sqrt(x) calculates the square root of x.

四舍五入函數

Lua provides several ways to round numbers:

number = 3.7

print(math.floor(number))  -- Outputs: 3 (rounds down)
print(math.ceil(number))   -- Outputs: 4 (rounds up)
print(math.round(number))  -- Outputs: 4 (rounds to nearest integer)

Think of floor as pushing the number down to the nearest whole number, ceil as pulling it up, and round as going to the nearest whole number.

隨機數

Generating random numbers is crucial for many programs, from games to simulations:

-- Generate a random number between 0 and 1
print(math.random())  -- Outputs: a random number like 0.54321

-- Generate a random integer between 1 and 10
print(math.random(1, 10))  -- Outputs: a random integer like 7

Remember to use math.randomseed(os.time()) at the start of your program to ensure truly random numbers each time you run it!

绝对值和符号

These functions help when dealing with positive and negative numbers:

print(math.abs(-5))   -- Outputs: 5
print(math.abs(5))    -- Outputs: 5
print(math.sign(-5))  -- Outputs: -1
print(math.sign(5))   -- Outputs: 1
print(math.sign(0))   -- Outputs: 0

math.abs gives the absolute (positive) value, while math.sign tells you if a number is positive (1), negative (-1), or zero (0).

結合所有知識

Let's create a small program that uses several of these functions:

math.randomseed(os.time())  -- Initialize random number generator

-- Generate two random numbers between 1 and 10
num1 = math.random(1, 10)
num2 = math.random(1, 10)

print("Our numbers are: " .. num1 .. " and " .. num2)

-- Calculate and round their average
average = (num1 + num2) / 2
rounded_average = math.floor(average)

print("The rounded down average is: " .. rounded_average)

-- Calculate the square root of their product
product = num1 * num2
sqrt_product = math.sqrt(product)

print("The square root of their product is: " .. sqrt_product)

-- Calculate the sine of their sum (in radians)
sum = num1 + num2
sin_sum = math.sin(sum)

print("The sine of their sum is: " .. sin_sum)

This program demonstrates how we can combine various math functions to perform more complex calculations.

結論

Congratulations! You've just taken your first steps into the world of Lua's Math Library. Remember, like any new skill, programming takes practice. Don't be afraid to experiment with these functions, combine them in different ways, and see what you can create.

Here's a table summarizing the functions we've covered:

Function Description
math.sin(x) Sine of x (x in radians)
math.cos(x) Cosine of x (x in radians)
math.tan(x) Tangent of x (x in radians)
math.asin(x) Arcsine of x (result in radians)
math.acos(x) Arccosine of x (result in radians)
math.atan(x) Arctangent of x (result in radians)
math.pow(x, y) x raised to the power y
math.sqrt(x) Square root of x
math.floor(x) Rounds x down to the nearest integer
math.ceil(x) Rounds x up to the nearest integer
math.round(x) Rounds x to the nearest integer
math.random() Generates a random number between 0 and 1
math.random(a, b) Generates a random integer between a and b
math.abs(x) Absolute value of x
math.sign(x) Sign of x (-1, 0, or 1)

Keep this table handy as a quick reference. Happy coding, and remember – in programming, as in math, practice makes perfect!

Credits: Image by storyset