Using the Math Object

To get some practice, this lesson's activities uses the console interactive mode.

Lesson Setup Instructions

Steps:

  1. Open in the web browser the console.html file found in the completed folder.

    Alternatively any open web page can be used.

  2. Open the Console window in the web developer tools.

    For details see the Using Web Browser Developer Tools to Learn lesson in the Getting Started section for interactively accessing the Chrome Console window.

1. Exploring the Math object.

The Math object has properties and methods for mathematical constants and functions.

Properties

  • Math.PI. Ratio of the circumference of a circle to its diameter, approximately 3.14159.

  • See full list here.

Methods

  • Math.ceil(x). Returns the smallest integer greater than or equal to a number.

  • Math.floor(x). Returns the largest integer less than or equal to a number.

  • Math.max([x[, y[, …]]]). Returns the largest of zero or more numbers.

  • Math.min([x[, y[, …]]]). Returns the smallest of zero or more numbers.

  • Math.random(). Returns a pseudo-random number between 0 and 1.

  • Math.round(x). Returns the value of a number rounded to the nearest integer.

  • Math.sqrt(x). Returns the positive square root of a number.

  • See full list here.

2. Lab: Working with the Math object.

  1. Math.PI

    Math.PI

    Compute the area of a circle.

    Circle area pi r squared.

    Math.PI * 3 * 3

    Math.PI in console.

  2. Math.max([x[, y[, …]]]) and Math.min([x[, y[, …]]])

    Math.max(100,200,10)
    Math.min(100,200,10)

    Math.max and Math.min in console.

  3. Math.ceil(x) and Math.floor(x).

    Math.ceil(3.4)
    Math.floor(3.4)
    Math.ceil(3.9)
    Math.floor(3.9)
    Math.ceil(1555/1000) * 1000
    Math.floor(1555/1000) * 1000

    Math.ceil and Math.floor in console.

  4. Math.random()

    Repeat several times.

    Math.random()

    Your results will differ.

    Math.random in console.

    Dice roll 1 - 6 formula. Repeat several times.

    Math.floor(Math.random() * 6) + 1

    Your results will differ.

    Math.random dice roll in console.

    Random range formula. Example 500 to 1000. Repeat several times.

    Math.floor(Math.random() * (1000 - 500 + 1)) + 500
    

    Your results will differ.

    Math.random range in console.

  5. Math.sqrt(x)

    Math.sqrt(2)
    Math.sqrt(9)

    Compute the hypotenuse of a triangle.

    Pythagorean Theorem

    Math.sqrt(169)

    Math.sqrt in console.

Complete and Continue