Assistance needed to convert polar distance formula to reverse Polish notation in Lisp

I’m trying to implement the polar coordinate distance formula in Lisp using reverse Polish notation. However, I’m struggling with the correct syntax and parentheses placement. Here’s my current attempt:

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

The problem is that the extra parentheses between subtraction and multiplication are altering the formula. I’m not sure how to structure it correctly to maintain the intended order of operations. Can someone help me fix this implementation or suggest a better approach? I want to make sure the math is accurate while keeping the code readable. Thanks in advance for any guidance!

hey, i think i can help. try this:

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

it’s simpler and keeps the math right. lemme know if u need more help!

I’ve implemented this formula in several projects, and here’s an approach that’s served me well:

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

This structure maintains mathematical accuracy while enhancing readability. It closely mirrors the standard formula layout, making it easier to verify and maintain. The key is grouping the subtraction as the outermost operation within the square root, which ensures correct calculation order.

Remember, in Lisp, each nested level of parentheses essentially creates a new scope for evaluation, so this arrangement preserves the intended mathematical sequence.

As someone who’s worked extensively with Lisp and mathematical implementations, I can offer some insights. Your approach is on the right track, but you’re correct that the parentheses placement is causing issues. Here’s a cleaned-up version that should work:

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

This maintains the correct order of operations and simplifies the structure. The key is to combine the addition and subtraction into a single addition operation with a negative term. Remember, in Lisp, operator precedence is determined by nesting, not by traditional mathematical rules. Each set of parentheses defines a new operation level.

I’ve found this approach to be both mathematically accurate and more readable. It’s closer to how you’d write it in mathematical notation, which can help when revisiting the code later or explaining it to others.