This is quite straightforward trigonometry; there is absolutely no reason (except a homework assignment -- it isn't that, is it?) to use recursion. If you're trying to do this in an effort to do OO programming, it would make more sense (as someone mentioned before) to use Math::Trig or use Math::Complex or completely horrify the Perlmonks and use Fortran Smalltalk.

The conversion formulae should be in any math book (I used Protter, MH and Morrey, CB College Calculus with Analytical Geometry, 2/ed, Addison Wesley Publishing, Co, Reading, Massachusetts: 1970, pp405-413).

The Perl below will compile and give answers (they may even be the right answers) but I will not guarantee efficiency, elegance, or attractiveness.

sub p2r { (my $r, my $theta) = @_; return ($r * cos($theta), $r * sin($theta)); # (x,y) } sub r2p { (my $x, my $y) = @_; my $theta = atan2($y, $x); my $r = ($x **2 + $y **2) ** (0.5); return ($r, $theta); }

Of course, $theta is in radians.

emc


In reply to Re: Constructing complex numbers using recursion by swampyankee
in thread Constructing complex numbers using recursion by moltar512

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.