Module: Kernel
- Defined in:
- lib/quaternion_c2/conversion.rb
Class Method Summary collapse
-
.Quaternion(*args) ⇒ Object
Returns a quaternion.
Class Method Details
.Quaternion(w, x, y, z) ⇒ Quaternion .Quaternion(a, b) ⇒ Quaternion .Quaternion(s, v) ⇒ Quaternion .Quaternion(str) ⇒ Quaternion
Returns a quaternion.
This function accepts various arguments except polar form. Strings are parsed to Numeric.
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 |
# File 'lib/quaternion_c2/conversion.rb', line 242 def Quaternion(*args) argc = args.size unless (1..4).cover?(argc) raise ArgumentError, "wrong number of arguments (given #{argc}, expected 1..4)" end if args.any?(&:nil?) raise TypeError, "can't convert nil into Quaternion" end # convert String into Numeric (strictly) args.collect! do |arg| case arg when String Quaternion.send(:parse, arg, true) else arg end end case argc when 1 arg = args[0] if arg.kind_of?(Numeric) # a quaternion (or an octonion, etc.) return arg.complex? ? arg.to_q : arg else raise TypeError, "can't convert #{arg.class} into Quaternion" end when 2 if args[1].kind_of?(Enumerable) # scalar and 3-D vector -> expand if args[1].size != 3 raise TypeError, "not a 3-D vector" end args.flatten!(1) elsif args.all? { |x| x.kind_of?(Numeric) && x.complex? } # a pair of complex numbers return Quaternion.send(:new, *args) else return args[0] + args[1] * Quaternion::J end end w, x, y, z = args z ||= 0 if args.all? { |x| x.kind_of?(Numeric) && x.real? } # 3 or 4 real numbers a = Complex.rect(w, x) b = Complex.rect(y, z) Quaternion.send(:new, a, b) else a = Complex(w, x) b = Complex(y, z) if [a, b].all? { |x| x.kind_of?(Numeric) && x.complex? } Quaternion.send(:new, a, b) else a + b * Quaternion::J end end end |