Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is sqrt() not a method on Numeric?

Tags:

oop

ruby

In Ruby everything is an object. That's why I don't understand why we have the Math module. It seems to me that most (all?) of the functions in the Math module should have been methods on the numeric types like Integer, Float and so on.

E.g. instead of

Math.sqrt(5) 

it would make more sense to have

5.sqrt 

The same goes for sin, cos, tan, log10 and so on.

Does anyone know why all these functions ended up in the Math module?

like image 889
KaptajnKold Avatar asked May 16 '10 16:05

KaptajnKold


People also ask

What type of method is math sqrt?

Math. sqrt() returns the square root of a value of type double passed to it as argument. If the argument is NaN or negative, then the result is NaN. If the argument is positive infinity, then the result is positive infinity.

What is the purpose of math sqrt () function?

The math. sqrt() method returns the square root of a number. Note: The number must be greater than or equal to 0.

How does sqrt function work in C?

The sqrt() function takes a single argument (in double ) and returns its square root (also in double ). The sqrt() function is defined in math. h header file. To find the square root of int , float or long double data types, you can explicitly convert the type to double using cast operator.

How do you implement a square root in Python?

sqrt() function is an inbuilt function in Python programming language that returns the square root of any number. Syntax: math. sqrt(x) Parameter: x is any number such that x>=0 Returns: It returns the square root of the number passed in the parameter.


1 Answers

I don't know the early history of Ruby, but I have a feeling the Math module was modelled after the C <math.h> header. It is an odd duck in the Ruby standard library though.

But, it's Ruby! So you can always bust out the monkey patching!

class Float   def sqrt; Math.sqrt(self); end   def sin; Math.sin(self); end   def cos; Math.cos(self); end   def tan; Math.tan(self); end   def log10; Math.log10(self); end end 
like image 175
Michael Melanson Avatar answered Oct 04 '22 13:10

Michael Melanson