Sorry for the long silence here, it’s been a busy summer with far too little Perl 6. But I did squeeze in some work on trig, both on nom and niecza. And I ran into a very interesting issue.
My local copy of niecza has S32-trig/sin.t almost working. A few needed skips, but all the core numeric types work. Except…
> is_approx(asin(0.785398163404734 + 2i), 0.341338918259482 + 1.49709293866352i # got: 2.80025373533031-1.49709293866352i # expected: 0.341338918259482+1.49709293866352i niecza> asin(0.785398163404734 + 2i) 2.80025373533031-1.49709293866352i rakudo> asin(0.785398163404734 + 2i) 0.341338918259481 + 1.49709293866352i
Woah, what’s up with that? Well, it turns out both answers are right in some sense:
niecza> sin(asin(0.785398163404734 + 2i)) 0.785398163404734+2i rakudo> sin(asin(0.785398163404734 + 2i)) 0.785398163404734 + 2i
The thing here is that
sin is periodic; there are an infinite number of complex numbers it maps to the same result value. That means when you call
asin, there are an infinite number of possible results for each input value, and you must somehow choose one of them.
But let’s take a step back from that and look at why I got different results, because I used the exact same formula for
asin in both Rakudo and Niecza. That formula is
-1i * log(($x)i + sqrt(1 - $x * $x)). Let’s look at the
niecza> my $x = 0.785398163404734 + 2i; sqrt(1 - $x * $x) -2.21086930051619+0.710488099157523i rakudo> my $x = 0.785398163404734 + 2i; sqrt(1 - $x * $x) 2.21086930051619 - 0.710488099157523i
As you can see, one answer is the negative of the other. Of course, when you square the results, that additional factor of
-1 just goes away, so these are both valid results.
So this leads me to two questions:
1) Should we define one of these two answers as being correct, as far as Perl 6 is concerned? (Or should they both be considered valid results?)
2) If so, which one? And how do we coherently specify that branch?
I thought at first it might be as simple as saying “The branch where the complex result of
sqrt for complex numbers with an imaginary value of 0 agrees with the real
sqrt result.” But in fact both Rakudo and Niecza already seem to agree for the
sqrts of real-valued Complex numbers.
Anyone else out there have a notion?