Reputation: 149
I would like to do smth like:
x `mod` 1.0 == 0 // => int
but it seems mod works only for int... help! EDIT: I am trying to check if given number is triangle, http://en.wikipedia.org/wiki/Triangle_number so my idea was to check if n1 is Int...
(n*(n+1))/2 = s => n1 = (-1 +sqrt(1 + 8s))/2
Upvotes: 1
Views: 5559
Reputation: 1679
To determine whether a certain Float
or Double
is indistinguishable from an Integer
in Haskell, use floor
and ceiling
together. Something like:
if floor n == ceiling n
then "It was some integer."
else "It's between integers."
There might also be some fancy stuff you can do with the float's representation in binary, exposed by the RealFloat typeclass:
http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#t%3ARealFloat
Upvotes: 7
Reputation: 77374
Total edit:
Okay, I'm still not sure what you're trying to accomplish here.
Data.Fixed
does have a mod'
function for non-integral values.mod
and sqrt
operations in the same calculation, you'll have to manually convert between appropriate types. fromIntegral
will convert any integer type into any number type, floor
, ceiling
, and round
will convert fractional types to integral types.Upvotes: 0
Reputation: 17786
A better way to check if a number is triangular is to generate a list of triangular numbers and then see if your candidate is in it. Since this is a learning problem I'm going to give hints rather than the answer.
Use a list comprehension to generate the triangular numbers.
Since they will be in order you can find out if you have gone past them.
An alternative approach if you are working with big numbers would be to use a binary search to narrow down the number of rows that might give rise to your candidate.
Upvotes: 2