Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixing abs for Rational{<:Unsigned} #29561

Merged
merged 5 commits into from
Oct 9, 2018
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Fix abs for Rational{<:Unsigned}
  • Loading branch information
lcontento authored Oct 8, 2018
commit 0e8abd4592ecd7e214071cf29a9e5d94c97d6b25
2 changes: 2 additions & 0 deletions base/rational.jl
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,8 @@ signbit(x::Rational) = signbit(x.num)
copysign(x::Rational, y::Real) = copysign(x.num,y) // x.den
copysign(x::Rational, y::Rational) = copysign(x.num,y.num) // x.den

abs(x::Rational{T}) where {T<:Unsigned} = x
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

An alternative approach (and maybe more general?) would be to define

abs(x::Rational) = Rational(abs(x.num), x.den)

but I don't know what is best.
I also wonder if the ifelse in numbers.jl could simply be a ternary, i.e.

abs(x::Real) = signbit(x) ? -x : x

since, as noted in this PR, not all numbers can be negated.

Copy link
Sponsor Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When T is unsigned, it is true that the ratio cannot be negative, so I guess this is fine. It's a bit weird to be using unsigned integers for rationals in the first place though, isn't it? I do think that @fredrikekre's suggestion for a generic definition that works for all rationals by calling abs on the numerator is better.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Indeed @fredrikekre's proposal appears to be more general. Should I add another commit to the same PR making the change or resubmit a cleaner one?

By the way, I was using unsigned rationals since it is a possible tag type for EXIF metadata. I agree that they are a strange choice in a general use case.

Copy link
Sponsor Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just add more commits here. Much easier that way. We can squash it when it’s ready.


typemin(::Type{Rational{T}}) where {T<:Integer} = -one(T)//zero(T)
typemax(::Type{Rational{T}}) where {T<:Integer} = one(T)//zero(T)

Expand Down