-
-
Notifications
You must be signed in to change notification settings - Fork 3
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
Arithmetic methods support for Angle
#16
Conversation
def +(other)
self.class.as_radians(radians + other.radians)
end This implementation doesn't allow for arithmetic operations with regular numbers: Astronoby::Angle.as_degrees(180) + 60
# `+': undefined method `radians' for 60:Integer (NoMethodError) I need to do the following: angle = Astronoby::Angle.as_degrees(180)
Astronoby::Angle.as_degrees(angle.degrees + 60) Do you think it would be worth it to allow somehow this? angle = Astronoby::Angle.as_degrees(180)
new_angle = angle + 60
new_angle.degrees # => 240 This would be very convenient to write, but also very error prone. I don't even know how to do it because angles are stored in radians and the This reminds me of your suggestion to implement Do you have an opinion? |
Co-authored-by: Joël Quenneville <[email protected]>
1e136b5
to
4cd6f65
Compare
Agreed! IMO you shouldn't do arithmetic operations with raw numbers. Raw numbers are ambiguous and lead to bugs. Consider: angle = Angle.as_degrees(180)
angle + 60 What does It's safer and easier to read if you do write this as: angle = Angle.as_degrees(180)
other_angle = Angle.as_degrees(60)
new_angle = angle + other_angle In general
Interestingly, the value returned by trigonometric functions is not a number of radians. It is not even an angle. Instead it is a unit-less number (a ratio of two distances so the units cancel out) The idea that you can do math between and across unit types, that this can result in new units, and that some operations are forbidden leads to the technique of dimensional analysis, where a calculation can be spot-checked for correctness by making sure that the units that come out of it are those expected Some languages like F# can track unit math automatically for you, which is pretty cool! |
6aa22d9
to
e463ade
Compare
This introduces several arithmetic functions in
Angle
to increase readability and developer experience.Instance methods
Angle#+
: adds two angles' values and returns an angleAngle#-
: subtracts two angles' values and returns an angleAngle#sin
: returns the numeric value (ratio) of the sine of the angleAngle#cos
: returns the numeric value (ratio) of the cosine of the angleAngle#tan
: returns the numeric value (ratio) of the tangent of the angle###Class methods
Angle::asin
: returns a new angle from the radians of a inverse sine ratioAngle::acos
: returns a new angle from the radians of a inverse cosine ratioAngle::atan
: returns a new angle from the radians of a inverse tangent ratioExamples