Learning Lua Step-By-Step: (Part 22)

This entry is part 21 of 25 in the series Learning Lua Step-By-Step

Post Stastics

  • This post has 982 words.
  • Estimated read time is 4.68 minute(s).

The Math Library

The Lua math library provides a comprehensive set of mathematical functions that are essential for various computations in Lua programs. This installment will delve into the Lua math library, covering its functions, usage examples, and best practices. We’ll also explore two example applications: a three-body simulation and a planetary simulation, both utilizing Lua’s math library for calculations.

Lua Math Library Functions

The Lua math library includes functions for basic arithmetic, trigonometry, exponentiation, logarithms, random number generation, and more. Here are some key functions:

  • math.abs(x): Returns the absolute value of x.
  • math.acos(x): Returns the arc cosine of x in radians.
  • math.asin(x): Returns the arc sine of x in radians.
  • math.atan(x): Returns the arc tangent of x in radians.
  • math.atan2(y, x): Returns the arc tangent of y/x in radians, using the signs of both parameters to determine the quadrant.
  • math.ceil(x): Returns the smallest integer greater than or equal to x.
  • math.cos(x): Returns the cosine of x (assumed to be in radians).
  • math.deg(x): Converts angle x from radians to degrees.
  • math.exp(x): Returns the exponential of x.
  • math.floor(x): Returns the largest integer less than or equal to x.
  • math.log(x): Returns the natural logarithm of x.
  • math.max(x, y, ...) and math.min(x, y, ...): Returns the maximum/minimum value among the arguments.
  • math.pow(x, y): Returns x raised to the power of y.
  • math.rad(x): Converts angle x from degrees to radians.
  • math.random([m [, n]]): Generates a pseudo-random number between m and n (inclusive).
  • math.randomseed(seed): Sets the seed for the random number generator.
  • math.sin(x): Returns the sine of x (assumed to be in radians).
  • math.sqrt(x): Returns the square root of x.
  • math.tan(x): Returns the tangent of x (assumed to be in radians).

Example Applications

Three-Body Simulation

Let’s create a simple three-body simulation using Lua and the math library. We’ll simulate the motion of three bodies in space and calculate their positions over time using Newtonian mechanics.

-- Three-Body Simulationlocal G = 6.67430e-11-- Gravitational constantfunction calculateForce(m1, m2, r)return G * m1 * m2 / (r^2)
endfunction updatePosition(body, dt)
    body.vx = body.vx + body.ax * dt
    body.vy = body.vy + body.ay * dt
    body.x = body.x + body.vx * dt
    body.y = body.y + body.vy * dt
end-- Initialize bodieslocal body1 = {x = 0, y = 0, vx = 0, vy = 10e3, ax = 0, ay = 0}
local body2 = {x = 1e8, y = 0, vx = 0, vy = -10e3, ax = 0, ay = 0}
local body3 = {x = 0, y = 1e8, vx = 10e3, vy = 0, ax = 0, ay = 0}

-- Simulate motionlocal dt = 1e3-- Time step in secondsfor t = 1, 100dolocal r12 = math.sqrt((body1.x - body2.x)^2 + (body1.y - body2.y)^2)
    local r13 = math.sqrt((body1.x - body3.x)^2 + (body1.y - body3.y)^2)
    local r23 = math.sqrt((body2.x - body3.x)^2 + (body2.y - body3.y)^2)

    local F12 = calculateForce(1e10, 1e10, r12)
    local F13 = calculateForce(1e10, 1e10, r13)
    local F23 = calculateForce(1e10, 1e10, r23)

    body1.ax = (F12 * (body2.x - body1.x) + F13 * (body3.x - body1.x)) / 1e10
    body1.ay = (F12 * (body2.y - body1.y) + F13 * (body3.y - body1.y)) / 1e10

    body2.ax = (-F12 * (body2.x - body1.x) + F23 * (body3.x - body2.x)) / 1e10
    body2.ay = (-F12 * (body2.y - body1.y) + F23 * (body3.y - body2.y)) / 1e10

    body3.ax = (-F13 * (body3.x - body1.x) - F23 * (body3.x - body2.x)) / 1e10
    body3.ay = (-F13 * (body3.y - body1.y) - F23 * (body3.y - body2.y)) / 1e10

    updatePosition(body1, dt)
    updatePosition(body2, dt)
    updatePosition(body3, dt)

    print("Time:", t * dt, "Body1:", body1.x, body1.y, "Body2:", body2.x, body2.y, "Body3:", body3.x, body3.y)
end

Planetary Simulation

Now, let’s create a planetary simulation using Lua and the math library. We’ll simulate the motion of planets around a central star using gravitational forces.

-- Planetary Simulationlocal G = 6.67430e-11-- Gravitational constantlocal starMass = 2e30-- Mass of the central starfunction calculateForce(m1, m2, r)return G * m1 * m2 / (r^2)
endfunction updatePosition(body, dt)
    body.vx = body.vx + body

.ax * dt
    body.vy = body.vy + body.ay * dt
    body.x = body.x + body.vx * dt
    body.y = body.y + body.vy * dt
end-- Initialize bodieslocal star = {x = 0, y = 0, vx = 0, vy = 0, ax = 0, ay = 0, mass = starMass}
local planets = {
    {x = 1.5e11, y = 0, vx = 0, vy = 3e4, ax = 0, ay = 0, mass = 5.97e24},  -- Earth
    {x = 2.9e11, y = 0, vx = 0, vy = 2.4e4, ax = 0, ay = 0, mass = 6.39e23},  -- Mars
    {x = 5.8e10, y = 0, vx = 0, vy = 4.7e4, ax = 0, ay = 0, mass = 3.3e23}  -- Mercury
}

-- Simulate motionlocal dt = 86400-- Time step in seconds (1 day)for t = 1, 365dofor _, planet inipairs(planets) dolocal r = math.sqrt((planet.x - star.x)^2 + (planet.y - star.y)^2)
        local F = calculateForce(star.mass, planet.mass, r)
        planet.ax = (F * (star.x - planet.x)) / planet.mass
        planet.ay = (F * (star.y - planet.y)) / planet.mass
        updatePosition(planet, dt)
    endprint("Time:", t * dt, "Planets:", planets[1].x, planets[1].y, planets[2].x, planets[2].y, planets[3].x, planets[3].y)
end

Exercises

  1. Write a Lua script that calculates the trajectory of a projectile launched at a certain angle and velocity.
  2. Implement a Lua program that simulates the behavior of a simple pendulum using trigonometric functions from the math library.
  3. Create a Lua function that computes the distance between two points in 2D space using the Pythagorean theorem.

Conclusion

The Lua math library empowers developers to perform complex mathematical calculations and simulations with ease. By harnessing the library’s functions, programmers can create simulations, solve mathematical problems, and build scientific applications efficiently. Practice and experimentation with these functions will enhance your understanding and proficiency in Lua programming.

Resources

Exploring these resources and engaging in mathematical simulations and calculations will broaden your programming horizons and enable you to tackle diverse computational challenges.

Series Navigation<< Learning Lua Step-By-Step: (Part 21)Learning Lua Step-By-Step: (Part 23) >>

Leave a Reply

Your email address will not be published. Required fields are marked *