Assistance needed for converting polar distance formula to Lisp RPN

Hey folks, I’m working on a Lisp program and I’m stuck trying to implement the polar coordinate distance formula. I’ve attempted to write a function, but I’m not sure if I’ve got the order of operations right in reverse Polish notation. Here’s what I’ve come up with so far:

(defun polar-distance (r1 r2 theta1 theta2)
  (setq result 
    (sqrt 
      (* 
        (- (+ (* r1 r1) (* r2 r2)) 
           (* 2 r1 r2))
        (cos (- theta1 theta2)))))
)

I think I might be messing up the parentheses, especially between the subtraction and multiplication parts. Can someone help me figure out the correct way to structure this in Lisp? I want to make sure I’m following the formula accurately. Thanks in advance for any tips or explanations!

hey claire, i noticed ur code mixes the order. try this:

defun polar-distance (r1 r2 theta1 theta2)
  (sqrt (+ (* r1 r1) (* r2 r2) (* -2 r1 r2 (cos (- theta1 theta2)))))

hope this clears it up!

Your approach was on the right track, but the formula implementation needed some tweaking. Here’s a refined version that should work correctly:

(defun polar-distance (r1 r2 theta1 theta2)
(sqrt (+ (expt r1 2)
(expt r2 2)
(- (* 2 r1 r2 (cos (- theta1 theta2)))))))

This structure maintains the correct order of operations for the polar distance formula. The ‘expt’ function is used for squaring r1 and r2, which is generally preferred over multiplication for clarity. Also, the subtraction is applied only to the cosine term, as per the standard formula.

Remember to test this function with various inputs to ensure it behaves as expected. If you encounter any issues or need further clarification, don’t hesitate to ask.

I’ve worked with Lisp and polar coordinates before, and I can see where you might be having issues. Your function is close, but there are a few adjustments needed. The main problem is in the order of operations and parentheses placement.

Here’s a corrected version based on the standard polar distance formula:

(defun polar-distance (r1 r2 theta1 theta2)
  (sqrt (+ (* r1 r1) 
           (* r2 r2) 
           (* -2 r1 r2 (cos (- theta1 theta2)))))

This structure ensures that you’re adding r1^2 and r2^2, then subtracting the 2r1r2cos(θ1-θ2) term. The sqrt function then wraps the entire expression.

Remember, in Lisp, the operator comes first in each expression. This can take some getting used to, but it allows for very clean nested expressions once you’re comfortable with it. Hope this helps with your implementation!