JavaScript Math 객체 메서드 탐구

JavaScriptBeginner
지금 연습하기

소개

이 랩에서는 참가자들이 JavaScript 의 Math 객체를 심층적으로 탐구하며, HTML 기반의 실습 시연을 통해 강력한 메서드와 속성을 살펴볼 것입니다. 이 랩은 Math.PI 및 Math.E 와 같은 내장 속성에 접근하고, 계산 메서드를 구현하며, 난수를 생성하고, 실용적인 시나리오에서 Math 객체 기술을 적용하는 등 다양한 수학적 연산을 보여주는 대화형 웹 페이지를 만드는 과정을 안내합니다.

단계별 접근 방식을 통해 학생들은 Math 객체 기능을 실험할 수 있는 JavaScript 가 내장된 HTML 파일을 구성하게 됩니다. Math.random(), Math.floor() 및 기타 수학적 유틸리티와 같은 메서드를 사용하는 방법을 배우고, 계산 문제를 해결하고 숫자 조작을 수행하기 위해 JavaScript 의 내장 수학적 기능을 활용하는 실질적인 경험을 얻게 될 것입니다.

Math 객체 데모를 위한 HTML 파일 설정

이 단계에서는 JavaScript 의 Math 객체 메서드를 시연하기 위한 HTML 파일을 생성합니다. Math 객체 기능을 탐색하고 실험할 수 있는 스크립트 섹션이 있는 기본 HTML 구조를 설정합니다.

WebIDE 를 열고 ~/project 디렉토리로 이동합니다. 다음 내용으로 math-demo.html이라는 새 파일을 생성합니다.

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>JavaScript Math Object Demonstration</title>
  </head>
  <body>
    <h1>Math Object Exploration</h1>
    <div id="output"></div>

    <script>
      // We'll add our Math object demonstrations here in the next steps
      const outputDiv = document.getElementById("output");

      function displayOutput(message) {
        outputDiv.innerHTML += `<p>${message}</p>`;
      }
    </script>
  </body>
</html>

이 HTML 파일의 주요 구성 요소를 살펴보겠습니다.

  1. 기본 HTML5 문서 구조를 생성했습니다.
  2. JavaScript 결과를 표시하기 위해 id="output"이 있는 <div>를 추가했습니다.
  3. Math 객체 시연을 작성할 <script> 섹션을 포함했습니다.
  4. 페이지에 결과를 쉽게 표시하기 위해 displayOutput() 도우미 함수를 생성했습니다.

이 파일을 브라우저에서 열 때의 예시 출력:

Math Object Exploration

displayOutput() 함수는 다음 단계에서 Math 객체 메서드의 결과를 쉽게 표시하는 데 도움이 됩니다. 이 설정은 JavaScript 의 Math 객체 기능을 탐색할 수 있는 깔끔하고 대화형 방식을 제공합니다.

Math 객체 속성 사용

이 단계에서는 JavaScript Math 객체의 내장 속성을 탐구합니다. 이전 단계에서 math-demo.html 파일을 열고 스크립트 섹션을 수정하여 이러한 속성을 시연합니다.

기존 <script> 섹션에 다음 코드를 추가합니다.

// Exploring Math Object Properties
displayOutput(`Math.PI: ${Math.PI}`);
displayOutput(`Math.E: ${Math.E}`);
displayOutput(`Euler's number (e): ${Math.E}`);
displayOutput(`Pi value: ${Math.PI}`);

// Demonstrating the use of these properties in a simple calculation
let circleRadius = 5;
let circleCircumference = 2 * Math.PI * circleRadius;
displayOutput(
  `Circle Circumference (radius ${circleRadius}): ${circleCircumference.toFixed(
    2
  )}`
);

JavaScript 의 Math 객체는 몇 가지 중요한 수학 상수를 제공합니다.

  1. Math.PI: 수학 상수 π (pi) 를 나타내며, 약 3.14159 입니다.
  2. Math.E: 오일러 수 (e) 를 나타내며, 약 2.71828 입니다.

HTML 파일을 브라우저에서 열면 다음과 유사한 출력이 표시됩니다.

Math.PI: 3.141592653589793
Math.E: 2.718281828459045
Euler's number (e): 2.718281828459045
Pi value: 3.141592653589793
Circle Circumference (radius 5): 31.42

이러한 속성은 수학적 계산, 특히 원, 지수 함수 및 기타 수학적 계산과 관련된 계산에 유용합니다.

계산을 위한 Math 객체 메서드 구현

이 단계에서는 수학적 계산을 수행하기 위해 다양한 Math 객체 메서드를 탐구합니다. math-demo.html 파일을 열고 다음 코드를 추가하여 다양한 Math 메서드를 시연합니다.

// Math Calculation Methods Demonstration
let number = -7.5;
let positiveNumber = Math.abs(number);
displayOutput(`Absolute Value of ${number}: ${positiveNumber}`);

let decimalNumber = 4.7;
let roundedDown = Math.floor(decimalNumber);
let roundedUp = Math.ceil(decimalNumber);
let rounded = Math.round(decimalNumber);
displayOutput(`Floor of ${decimalNumber}: ${roundedDown}`);
displayOutput(`Ceiling of ${decimalNumber}: ${roundedUp}`);
displayOutput(`Rounded of ${decimalNumber}: ${rounded}`);

let baseNumber = 2;
let exponent = 3;
let powerResult = Math.pow(baseNumber, exponent);
displayOutput(
  `${baseNumber} raised to the power of ${exponent}: ${powerResult}`
);

let largestNumber = Math.max(10, 5, 8, 12, 3);
let smallestNumber = Math.min(10, 5, 8, 12, 3);
displayOutput(`Largest number: ${largestNumber}`);
displayOutput(`Smallest number: ${smallestNumber}`);

let squareRoot = Math.sqrt(16);
displayOutput(`Square root of 16: ${squareRoot}`);

이 코드는 몇 가지 주요 Math 객체 메서드를 시연합니다.

  1. Math.abs(): 숫자의 절대값을 반환합니다.
  2. Math.floor(): 가장 가까운 정수로 내림합니다.
  3. Math.ceil(): 가장 가까운 정수로 올림합니다.
  4. Math.round(): 가장 가까운 정수로 반올림합니다.
  5. Math.pow(): 숫자를 지정된 거듭제곱으로 올립니다.
  6. Math.max(): 목록에서 가장 큰 숫자를 반환합니다.
  7. Math.min(): 목록에서 가장 작은 숫자를 반환합니다.
  8. Math.sqrt(): 숫자의 제곱근을 계산합니다.

예시 출력:

Absolute Value of -7.5: 7.5
Floor of 4.7: 4
Ceiling of 4.7: 5
Rounded of 4.7: 5
2 raised to the power of 3: 8
Largest number: 12
Smallest number: 3
Square root of 16: 4

Math.random() 으로 난수 생성

이 단계에서는 Math.random()을 사용하여 난수를 생성하는 방법과 보다 진보된 난수 생성 기술을 만드는 방법을 탐구합니다. math-demo.html 파일을 열고 다음 코드를 추가하여 난수 생성을 시연합니다.

// Random Number Generation Demonstration
// Basic random number (between 0 and 1)
let basicRandom = Math.random();
displayOutput(`Basic Random Number: ${basicRandom}`);

// Generate random number in a specific range
function getRandomNumber(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

// Random integer between 1 and 10
let randomInt = getRandomNumber(1, 10);
displayOutput(`Random Integer (1-10): ${randomInt}`);

// Generate multiple random numbers
displayOutput("Five Random Numbers (1-100):");
for (let i = 0; i < 5; i++) {
  let randomNumber = getRandomNumber(1, 100);
  displayOutput(randomNumber);
}

// Simulating a coin flip
function coinFlip() {
  return Math.random() < 0.5 ? "Heads" : "Tails";
}
displayOutput(`Coin Flip Result: ${coinFlip()}`);

// Random color generator
function getRandomColor() {
  let r = getRandomNumber(0, 255);
  let g = getRandomNumber(0, 255);
  let b = getRandomNumber(0, 255);
  return `rgb(${r}, ${g}, ${b})`;
}
displayOutput(`Random Color: ${getRandomColor()}`);

예시 출력은 다음과 같습니다.

Basic Random Number: 0.7234567890123456
Random Integer (1-10): 7
Five Random Numbers (1-100):
42
15
83
61
29
Coin Flip Result: Heads
Random Color: rgb(134, 45, 211)

Math.random()에 대한 주요 사항:

  • 0 (포함) 과 1 (제외) 사이의 의사 난수를 반환합니다.
  • 특정 범위의 숫자를 생성하기 위해 크기를 조정하고 조작할 수 있습니다.
  • 게임, 시뮬레이션 및 무작위 선택에 유용합니다.

실제 시나리오에서 Math 객체 메서드 적용

이 단계에서는 실제 시나리오에서 Math 객체 메서드의 실용적인 적용을 탐구합니다. math-demo.html 파일을 열고 다음 코드를 추가하여 실용적인 사용 사례를 시연합니다.

// Practical Scenarios with Math Object Methods

// 1. Calculate Discount Price
function calculateDiscount(originalPrice, discountPercentage) {
  let discountAmount = originalPrice * (discountPercentage / 100);
  let finalPrice = originalPrice - discountAmount;
  displayOutput(`Original Price: $${originalPrice.toFixed(2)}`);
  displayOutput(
    `Discount (${discountPercentage}%): $${discountAmount.toFixed(2)}`
  );
  displayOutput(`Final Price: $${finalPrice.toFixed(2)}`);
  return finalPrice;
}
calculateDiscount(100, 20);

// 2. Circle Area Calculator
function calculateCircleArea(radius) {
  let area = Math.PI * Math.pow(radius, 2);
  displayOutput(`Circle Radius: ${radius}`);
  displayOutput(`Circle Area: ${area.toFixed(2)} sq units`);
  return area;
}
calculateCircleArea(5);

// 3. Temperature Converter (Celsius to Fahrenheit)
function celsiusToFahrenheit(celsius) {
  let fahrenheit = Math.round((celsius * 9) / 5 + 32);
  displayOutput(`${celsius}°C is ${fahrenheit}°F`);
  return fahrenheit;
}
celsiusToFahrenheit(25);

// 4. Hypotenuse Calculator
function calculateHypotenuse(a, b) {
  let hypotenuse = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
  displayOutput(`Triangle Sides: ${a}, ${b}`);
  displayOutput(`Hypotenuse Length: ${hypotenuse.toFixed(2)}`);
  return hypotenuse;
}
calculateHypotenuse(3, 4);

// 5. Random Score Generator for a Quiz
function generateQuizScores(numberOfStudents) {
  displayOutput(`Quiz Scores for ${numberOfStudents} students:`);
  for (let i = 1; i <= numberOfStudents; i++) {
    let score = Math.floor(Math.random() * 51) + 50; // Scores between 50-100
    displayOutput(`Student ${i}: ${score}`);
  }
}
generateQuizScores(5);

예시 출력은 다음과 같습니다.

Original Price: $100.00
Discount (20%): $20.00
Final Price: $80.00
Circle Radius: 5
Circle Area: 78.54 sq units
25°C is 77°F
Triangle Sides: 3, 4
Hypotenuse Length: 5.00
Quiz Scores for 5 students:
Student 1: 75
Student 2: 92
Student 3: 63
Student 4: 87
Student 5: 69

이 시연은 Math 객체 메서드를 다양한 실용적인 시나리오에 적용하는 방법을 보여줍니다.

  • 할인 계산
  • 기하학적 면적 계산
  • 온도 변환
  • 빗변 길이 찾기
  • 난수 점수 생성

요약

이 랩에서는 참가자들이 실습 HTML 데모를 통해 JavaScript Math 객체의 기능을 탐구합니다. 랩은 전용 출력 div 와 결과를 표시하는 도우미 함수를 사용하여 대화형 HTML 파일을 설정하는 것으로 시작하여 수학적 연산 및 메서드를 학습하기 위한 구조화된 환경을 제공합니다.

학습 과정은 Math 객체의 주요 측면을 다룹니다. Math.PI 및 Math.E 와 같은 내장 속성을 검토하고, 반올림, 최대값 및 최소값 찾기, 난수 생성과 같은 계산 메서드를 구현합니다. HTML 스크립트 섹션에 코드를 점진적으로 추가함으로써 학습자는 JavaScript 의 수학적 유틸리티에 대한 실질적인 경험을 얻고, 이러한 메서드를 다양한 계산 작업 및 실제 프로그래밍 시나리오에 활용하는 방법을 이해합니다.