Type class Integral has two operations quot and div, yet in the Haskell 2010 Language Report it is not specified what they're supposed to do. Assuming that div is integral division, what does quot differently, or what is the purpose of quot? When do you use one, and when the other?
To quote section 6.4.2 from the Haskell report:
The quot, rem, div, and mod class methods satisfy these laws if y is non-zero:
(x `quot` y)*y + (x `rem` y) == x
(x `div` y)*y + (x `mod` y) == x
quot is integer division truncated toward zero, while the result of div is truncated toward negative infinity.
The div function is often the more natural one to use, whereas the quot function corresponds to the machine instruction on modern machines, so it's somewhat more efficient.
The two behave differently when dealing with negative numbers. Consider:
Hugs> (-20) `divMod` 3
(-7,1)
Hugs> (-20) `quotRem` 3
(-6,-2)
Here, -7 * 3 + 1 = -20 and -6 * 3 + (-2) = -20, but the two ways give you different answers.
Also, see here: http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html
The definition for quot is "integer division truncated toward zero", whereas the definition for div is "integer division truncated toward negative infinity".
Related
I am trying to write a program in Haskell that returns 'e' (Euler's number) to a given decimal place. Here is my code so far:
factorial 0 = 1
factorial n = n * factorial (n - 1)
calculateE a
| a == 0 = 1
| otherwise = nextLevel
where nextLevel = (1 / (factorial a)) + calculateE (a-1)
Whenever I call calculateE I only get back 16 decimal places. Is this a limitation of Haskell/My computer? Is there a way to get back any number of decimal places?
This code already works to arbitrary precision. You just need to use an arbitrary precision type and not the standard Float/Double. Haskell's standard library has Rational for this purpose, which represents rational numbers as pairs of integers.
ghci> calculateE 100 :: Rational
4299778907798767752801199122242037634663518280784714275131782813346597523870956720660008227544949996496057758175050906671347686438130409774741771022426508339 % 1581800261761765299689817607733333906622304546853925787603270574495213559207286705236295999595873191292435557980122436580528562896896000000000000000000000000
The issue now is getting a sequence of digits out of it. I'm not aware of anything in the standard library that does it, so here's a stupid simple (might still be buggy!) implementation:
import Data.List(unfoldr)
import Data.List.NonEmpty(NonEmpty((:|)))
import Data.Ratio
-- first element is integral part (+ sign), rest are positive and < 10 and are digits
-- after the decimal point (for negative numbers, these digits should be seen as having negative value)
longDivision :: Integral a => Ratio a -> NonEmpty a
longDivision x = hi :| unfoldr go (abs lo)
where (hi, lo) = numerator x `quotRem` denominator x
go 0 = Nothing
go lo = Just $ (lo * 10) `quotRem` denominator x
printDigits :: Show a => NonEmpty a -> String
printDigits (x :| xs) = show x ++ "." ++ concatMap show xs
So
ghci> take 100 $ printDigits $ longDivision $ calculateE 100
"2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852516642"
This approximation actually seems to be good to ~160 digits after the decimal point.
I'm learning Haskell and I have been practising doing some functions by myself, in this functions are included the calculus of sine using recursion, but I get strange results.
The formula I'm using to calculate the sine is this one:
And my code is this:
--Returns n to power p
pow :: Float->Integer->Float
pow n p =
if p == 0 then
1
else
if p == 1 then
n
else
n * (pow n (p-1))
--Finds a number's factorial
f :: Integer->Integer
f n =
if n == 1 then
n
else
n * (f (n-1))
--TODO: Trigonometric functions ( :v I'll do diz 2)
sinus :: Float->Char->Float
sinus n deg =
if(deg == 'd')then
sinusr 0 (normalize (torad n)) 0
else
sinusr 0 (normalize n) 0
--Get the value equivalent to radians of the presented degrees
torad :: Float->Float
torad v = ( (v * pi) / 180 )
--Recursive to get the value of the entering radians
sinusr :: Integer->Float->Float->Float
sinusr k x result =
if k == 130 then
result + ( ((pow (-1) k ) * ((pow x ((2*k)+1))) / (fromIntegral (f ((2*k)+1)))))
else
result + (sinusr (k+1) x ( ((pow (-1) k ) * ((pow x ((2*k)+1))) / (fromIntegral (f ((2*k)+1))))))
--Subtracts pi/2 the necessary times to get a value minor or equals to pi/2 :v
normalize :: Float->Float
normalize a = a - (fromIntegral (truncate (a / (pi*2)))*(pi*2))
For example, the output it's this:
*Main> sinus 1 'd'
1.7452406e-2
*Main> sinus 1 's'
0.84147096
*Main> sinus 2 's'
NaN
*Main> sinus 2 'd'
3.4899496e-2
Can someone tell me why it is showing me that?
I have worked the same logic with Lisp, and it runs perfectly, I just had to figure out the Haskell syntax, but as you can see, it is not working as it must be.
Beforehand, thank you very much.
Single point arithmetic isn't accurate enough for to calculate a trigonometric function. The exponent doesn't have enough bits for the large, intermediate numbers in sinusr. Or, to be blunt, the following number doesn't fit a Float:
ghci> 2 ^ 130 :: Float
Infinity
As soon as you hit the boundaries of floating point numbers (-Infinity, Infinity) you usually end up with either those or NaN.
Use Double instead. Your implementation of lisp probably uses double point precision floating point numbers too. Even better, don't recalculate the whole fraction in every step, instead update the nominator and denominator, then your values won't get too large for Float.
I started learning Haskell recently and in my class right now, we have constructed a Peano number class and instanced it in the Num typeclass.
During lecture, my professor claimed that depending on whether you viewed the successor function as S x = x + 1 or S x = 1 + x, the appropriate successor case for the multiplication definition would be different. Respectively:
x * S y = x * y + x
x * S y = x + x * y
Moreover, he claimed that using the first of these two choices is preferable because it is lazier but I'm having trouble seeing how this is the case.
We looked at the example in which the addition definition of
x + S y = S (x + y)
is better than
x + S y = S x + y
because evaluating x + y == z occurs much faster but I can't find an analogous case for multiplication.
The lecture notes are here: http://cmsc-16100.cs.uchicago.edu/2014/Lectures/lecture-02.php
Laziness is not about speed but what is available how soon.
With x * S y = x * y + x then you can answer infinity * 2 > 5 very quickly, because it will expand as so:
infinity * (S (S Z)) > 5
infinity * (S Z) + infinity > 5
infinity * Z + infinity + infinity > 5
infinity + infinity > 5
(from there the rest is trivial)
However, I don't think it is all as good as your professor claimed! Try to expand out 2 * infinity > 5 in this formalism and you'll be disappointed (or busy for a very long time :-P). On the other hand, with the other definition of multiplication, you do get an answer there.
Now, if we have the "good" definition of addition, I think it should be the case that you can get an answer with infinities in either position. And indeed, I checked the source of a few Haskell packages that define Nats, and indeed they prefer x * S y = x + x * y rather than the way your professor claimed was better.
I've been wanting to learn Haskell, so recently I started working through the ProjectEuler problems. While writing the following factoring code I noticed that calling (/ n) returns a Float while (n `div`) returns an Int. I thought that infix notation was simply syntactic sugar in Haskell? Could someone explain what is going on? I would also appreciate any comments / suggestions / improvements, thank you.
import Data.List (sort)
factor :: Int -> [Int]
factor 0 = [1..]
factor n =
let f1 = [f | f <- [1..limit], n `mod` f == 0]
where limit = ceiling $ sqrt $ fromIntegral n
f2 = map (n `div`) f1 --vs. map (/ n) f1
in sort $ f1 ++ f2
div and / are two different functions:
/ is defined in class Fractional and it's meaning is an inverse operation to multiplication.
div is defined in class Integral and it's meaning is division of integers with truncation toward negative infinity.
You're right, infix notation is just a syntactic sugar. The expression x / y is the same as (/) x y, as well as div x y is the same as x `div` y.
There's nothing special going on. The div function is part of the Integral class and is being more specifically inferred as Int, given your explicit type signature. The / operator is part of the Fractional class. These are two different functions, one is not syntactic sugar for another!
From the haskell report:
The quot, rem, div, and mod class
methods satisfy these laws if y is
non-zero:
(x `quot` y)*y + (x `rem` y) == x
(x `div` y)*y + (x `mod` y) == x
quot is integer division truncated
toward zero, while the result of div
is truncated toward negative infinity.
For example:
Prelude> (-12) `quot` 5
-2
Prelude> (-12) `div` 5
-3
What are some examples of where the difference between how the result is truncated matters?
Many languages have a "mod" or "%" operator that gives the remainder after division with truncation towards 0; for example C, C++, and Java, and probably C#, would say:
(-11)/5 = -2
(-11)%5 = -1
5*((-11)/5) + (-11)%5 = 5*(-2) + (-1) = -11.
Haskell's quot and rem are intended to imitate this behaviour. I can imagine compatibility with the output of some C program might be desirable in some contrived situation.
Haskell's div and mod, and subsequently Python's / and %, follow the convention of mathematicians (at least number-theorists) in always truncating down division (not towards 0 -- towards negative infinity) so that the remainder is always nonnegative. Thus in Python,
(-11)/5 = -3
(-11)%5 = 4
5*((-11)/5) + (-11)%5 = 5*(-3) + 4 = -11.
Haskell's div and mod follow this behaviour.
This is not exactly an answer to your question, but in GHC on x86, quotRem on Int will compile down to a single machine instruction, whereas divMod does quite a bit more work. So if you are in a speed-critical section and working on positive numbers only, quotRem is the way to go.
A simple example where it would matter is testing if an integer is even or odd.
let buggyOdd x = x `rem` 2 == 1
buggyOdd 1 // True
buggyOdd (-1) // False (wrong!)
let odd x = x `mod` 2 == 1
odd 1 // True
odd (-1) // True
Note, of course, you could avoid thinking about these issues by just defining odd in this way:
let odd x = x `rem` 2 /= 0
odd 1 // True
odd (-1) // True
In general, just remember that, for y > 0, x mod y always return something >= 0 while x rem y returns 0 or something of the same sign as x.