Skip to main content
Known Participant
November 11, 2024
Question

Help converting JavaScript code to ECMAScript 3

  • November 11, 2024
  • 1 reply
  • 209 views

Help converting JavaScript code to ECMAScript 3 to solve the angle 𝑎⋅𝑏|𝑎||𝑏|=cos𝜃 where  X0 Y0 . X0 Y20

 

// What is the angle?
// 𝑎⋅𝑏|𝑎||𝑏|=cos𝜃,  X0 Y0 . X0 Y20

function cosineTheta(a, b) {
  let dotProduct = 0;
  let aMagnitude = 0;
  let bMagnitude = 0;

  // Calculate dot product
  for (let i = 0; i < a.length; i++) {
    dotProduct += a[i] * b[i];
  }

  // Calculate magnitudes
  for (let i = 0; i < a.length; i++) {
    aMagnitude += a[i] * a[i];
    bMagnitude += b[i] * b[i];
  }

  aMagnitude = Math.sqrt(aMagnitude);
  bMagnitude = Math.sqrt(bMagnitude);

  // Calculate cosine
  return dotProduct / (aMagnitude * bMagnitude);
}

// Example usage needs to solve for X0 Y0 . X0 Y20 in 2D plane
// where the resulting angle between the vectors a and b is 90°
const vectorA = [1, 2, 3];
const vectorB = [4, 5, 6];

const cosTheta = cosineTheta(vectorA, vectorB);
console.log(cosTheta);

 

This topic has been closed for replies.

1 reply

nutradialAuthor
Known Participant
November 11, 2024
// cos(θ) = (a · b) / (||a|| * ||b||)

function angleBetweenVectors(x1, y1, x2, y2) {
  // Calculate the dot product
  const dotProduct = x1 * x2 + y1 * y2;

  // Calculate the magnitudes
  const magnitude1 = Math.sqrt(x1 * x1 + y1 * y1);
  const magnitude2 = Math.sqrt(x2 * x2 + y2 * y2);

  // Calculate the cosine of the angle
  const cosTheta = dotProduct / (magnitude1 * magnitude2);

  // Calculate the angle in radians
  const angleInRadians = Math.acos(cosTheta);

  // Convert to degrees (if needed)
  const angleInDegrees = (angleInRadians * 180) / Math.PI;

  return angleInDegrees;
}

// Example usage for your vectors:
const angle = angleBetweenVectors(0, 0, 0, 20);
console.log(angle); // Output: 90 degrees
nutradialAuthor
Known Participant
November 12, 2024

I thought my script was not working due to JavaScript compatibility but I now realize that that is not the case. Also, this is probably not the place to look for these kinds of answers but if anyone is curious I need the ExtendScript formula for a path's tangential angle that resolves in degrees.