Skip to main content

5. 7 Summarizing with reduce

 Summarizing with reduce   Understanding Reduce Purpose of Reduce : reduce is a higher-order function used to compute a single value from an array. It's instrumental in operations like summing up numbers or finding an item in an array that meets a specific criterion (e.g., the script with the most characters). Operation : It works by repeatedly taking an element from the array and combining it with a current value until all elements have been processed. This process is akin to folding or reducing the array into a single value. 🎨: Think of reduce like making juice from oranges. You start with a bunch of oranges (the array), and then you squeeze them one by one into a jug (the single value). Your hands (the combining function) do the squeezing, and you might already have some juice in the jug to start with (the start value). 👩‍🎓: The Mechanics of reduce - The reduce function takes three arguments: the array to reduce, a combining function, and a starting value. The combin...

4.13 The Math object

 

The Math object

 

🔍: This section  offers a detailed overview of the JavaScript Math object, explaining its purpose, usage, and some key methods. Let's break this down using the Feynman Technique and First Principles thinking.

👩‍🎓: Understanding the Math Object:

  1. Purpose and Nature of Math Object:

    • Math is a built-in object in JavaScript that groups together various methods and properties related to mathematical operations. It acts as a namespace, which means it's a container for these methods and constants to avoid polluting the global scope.
    • It's not an object in the sense of storing data, but more of a utility object providing mathematical functionality.
  2. Preventing Namespace Pollution:

    • By containing functions like max, min, sqrt, etc., within the Math object, JavaScript reduces the risk of naming conflicts in the global namespace. This means you can use names like max in your code without worrying about overwriting the built-in JavaScript function.
  3. Trigonometry Functions:

    • Math includes trigonometric functions like cos (cosine), sin (sine), tan (tangent), and their inverses (acos, asin, atan).
    • Math.PI provides the value of π (pi).
  4. Random Numbers:

    • Math.random generates pseudorandom numbers between 0 (inclusive) and 1 (exclusive).
    • The randomness is achieved through internal algorithms, making the numbers appear random though they are computed.
  5. Rounding Methods:

    • Math.floor: Rounds down to the nearest whole number.
    • Math.ceil ("ceiling"): Rounds up to the nearest whole number.
    • Math.round: Rounds to the nearest whole number.
    • Math.abs: Returns the absolute value of a number (negates negative values, leaves positive ones unchanged).

🎨: Practical Example - Random Point on a Circle:

  • The randomPointOnCircle function illustrates using Math.random along with trigonometric functions. It generates a random angle, then calculates a point's coordinates on a circle of given radius at that angle.

🔄: Using Math in Programming:

  • These mathematical tools are essential for various programming tasks, from simple operations like generating random numbers to complex calculations involving trigonometry.
  • The Math object encapsulates these tools in a way that's easy to access and use, without needing to implement common mathematical functions from scratch.

🧠: Conclusion:

  • The Math object in JavaScript is a powerful toolkit for mathematical operations essential in programming. Its design as a namespace is beneficial for both functionality and avoiding global scope pollution.

⚙️: Exploring Further:

If you have specific questions about any of these Math function it is needed to check their explanations.

Thew3schools site is a good place to start for easy and intuitive explanations
 
 

Code Explanation

🧠 Understanding the Code Conceptually:

  • The code leverages the circular symmetry and trigonometric functions to pick a random point on the circle’s edge. It's like spinning a wheel and marking the point where it stops.

This function effectively demonstrates how mathematics can be applied in programming to solve geometric problems, such as randomly placing objects within a circular boundary.


function randomPointOnCircle(radius) {
  let angle = Math.random() * 2 * Math.PI;
  return {x: radius * Math.cos(angle),
          y: radius * Math.sin(angle)};
}
console.log(randomPointOnCircle(2));
// → {x: 0.3667, y: 1.966}

This code defines a function randomPointOnCircle(radius) that generates a random point on the circumference of a circle with the given radius. The function returns an object with two properties, x and y, representing the coordinates of this random point. Here's a step-by-step explanation:

  1. Function Definition: randomPointOnCircle(radius) is a function that takes one parameter radius. This radius is the distance from the center of the circle to any point on its circumference.

  2. Generating a Random Angle:

    • let angle = Math.random() * 2 * Math.PI;
    • Math.random() generates a random decimal number between 0 and 1. This number is then multiplied by 2 * Math.PI.
    • Math.PI is a constant in JavaScript that represents the value of π (pi), approximately 3.14159.
    • The product 2 * Math.PI represents the full range of angles in a circle, measured in radians (from 0 to approximately 6.28318, which is 360 degrees in radian measure).
  3. Calculating Coordinates:

    • The function then calculates the x and y coordinates of the point on the circle's circumference using trigonometric functions.
    • radius * Math.cos(angle) computes the x-coordinate. The cosine of an angle in a circle gives the horizontal (x) distance of a point from the circle’s center.
    • radius * Math.sin(angle) computes the y-coordinate. The sine of an angle in a circle gives the vertical (y) distance of a point from the circle’s center.
  4. Returning the Point:

    • The function returns an object {x: ..., y: ...} with these x and y coordinates.
  5. Example Usage:

    • console.log(randomPointOnCircle(2));
    • This line calls the function with a radius of 2, and prints the result to the console.
    • The output, like {x: 0.3667, y: 1.966}, represents a random point on the circumference of a circle with radius 2.

🔍 Mathematical Background: converting polar coordinates to Cartesian coordinates

  • A circle is defined as the set of all points that are a fixed distance (radius) from a central point.
  • An angle measured in radians describes a segment of the circle's circumference. One complete revolution around a circle is 2π radians (or 360 degrees).
  • Math.cos(angle) and Math.sin(angle) are trigonometric functions that return the cosine and sine of an angle, respectively. In the context of a circle, they are used to find coordinates relative to the circle's center.
Let's dive into the math behind converting polar coordinates to Cartesian coordinates. The formulas x = r * cos(θ) and y = r * sin(θ) are used for this conversion. Here's a step-by-step explanation:
  1. Polar Coordinates: In polar coordinates, a point is represented by two values: the radius r and the angle θ (theta). The radius r is the distance from the origin to the point, and the angle θ is the direction of the radius measured from the positive x-axis, usually in radians.

  2. Cartesian Coordinates: In Cartesian coordinates, a point is represented by an x and y value, which are the distances along the x-axis and y-axis, respectively.

  3. Conversion Process: The conversion from polar to Cartesian coordinates is based on trigonometric functions.

     

    • x = r * cos(θ): This formula finds the horizontal distance (x-coordinate) of the point.

      • The cosine of an angle in a right triangle is defined as the ratio of the adjacent side (here, x-coordinate) to the hypotenuse (here, radius r).
      • So, cos(θ) = adjacent/hypotenuse = x/r.
      • Rearranging this, we get x = r * cos(θ).
    • y = r * sin(θ): This formula finds the vertical distance (y-coordinate) of the point.

      • The sine of an angle in a right triangle is the ratio of the opposite side (here, y-coordinate) to the hypotenuse (radius r).
      • So, sin(θ) = opposite/hypotenuse = y/r.
      • Rearranging this, we get y = r * sin(θ).

🔍: To visualize this, imagine a circle with a radius r. If you pick a point on the circumference and draw a line from the center of the circle to this point, the length of this line is r. The angle θ is the angle formed by this line and the positive x-axis. The x-coordinate of this point is the horizontal distance from the y-axis, which is r times the cosine of θ. Similarly, the y-coordinate is the vertical distance from the x-axis, which is r times the sine of θ.


🔄: The beauty of these formulas lies in their ability to seamlessly translate the circular, rotational motion described by polar coordinates into the rigid, grid-like structure of Cartesian coordinates, bridging two fundamentally different ways of describing positions in space.

Further reference: I recommend this source for addiction details:
https://www.mathsisfun.com/sine-cosine-tangent.html

 

Comments