- Sponsor
-
Notifications
You must be signed in to change notification settings - Fork 5.6k
Closed
Labels
mathsMathematical functionsMathematical functionsspeculativeWhether the change will be implemented is speculativeWhether the change will be implemented is speculative
Description
The mathematical expression (-1)^n
appears in many equations. It would be convenient to have an efficient standard implementation in Julia. This is, in effect, the inverse of the signbit
function.
I propose the following implementation:
function bitsign(b::Bool)::Int
1 - 2 * b # this seems to be the most efficient way
end
function bitsign(b::I)::I where {I<:Signed}
I(bitsign(isodd(b)))
end
stevengj and StefanKarpinski
Metadata
Metadata
Assignees
Labels
mathsMathematical functionsMathematical functionsspeculativeWhether the change will be implemented is speculativeWhether the change will be implemented is speculative
Type
Projects
Milestone
Relationships
Development
Select code repository
Activity
StefanKarpinski commentedon Sep 26, 2019
Would this be generalized to complex powers as well?
eschnett commentedon Sep 26, 2019
@StefanKarpinski Are you looking for
cis
? Maybe a new functioncispi
, similar tosinpi
andcospi
?StefanKarpinski commentedon Sep 26, 2019
I'm not looking for anything, just trying to reason about the function you've proposed. If the definition is that it computes
(-1)^n
then the fact that it always returns ±1 for integer values is a specialization; for complex arguments it should compute the more general function. Similarly, consider the behavior ofsign
for a complex argument:eschnett commentedon Sep 27, 2019
@StefanKarpinski I see; going for a generic definition makes sense. Of course, the efficient implementation (much more efficient than actually calculating
(-1)^n
) exists only for integern
.If you allow the exponent to be any real or complex number, then the implementation would be
(-1)^x = exp(im*pi*x) = cis(pi*x)
. That's also an expression that occurs frequently. The namebitsign
doesn't work any more here.StefanKarpinski commentedon Sep 27, 2019
Right, that's part of why I was asking—the name seemed a bit too specific to the implementation. I think calling it
cispi
might be good and mentioning it in the help text ofsignbit
. I guess the biggest worry is that it's pretty non-obvious to most people thatcispi(n)
is(-1)^n
.StefanKarpinski commentedon Sep 27, 2019
It's also kind of amazing and unexpected that
cispi
is the inverse function ofsignbit
.eschnett commentedon May 6, 2020
I just realize that we don't need
cispi
, the existingcospi
will do fine. Should we instead add a method forcospi
(andsinpi
, for symmetry) that acts on integers or booleans?sinpi
andcospi
return integers for integer input? #35820vtjnash commentedon Feb 16, 2022
No consensus that this is something desired (rejected from #35792)