Haskell rounding numbers to 2 decimals [duplicate] - haskell

This question already has answers here:
Round number to specified number of digits
(3 answers)
Closed 3 months ago.
I am trying to round a number to two digits in haskell,
so if the output let's say is 1.98887779, I want it to only outpus 1.98.
note that I already have a function and I want the round to happen around an operation.
thanks
I have tried
round $
but it's not working properly.

I am trying to round a number to two digits in Haskell, so if the
output let's say is 1.98887779, I want it to only outpts 1.98
If you round that number to two decimal places, it should end up with 1.99.
The way to round a number x to a given number of decimal places n is to:
multiply x by 10 raised to the power of n
round this value
divided it by 10 raised to the power of n
Thus:
tenPow :: Integer -> Float
tenPow n = 10.0 ^ n
roundN :: Float -> Integer -> Float
roundN x n = (fromIntegral . round) (x * tenPow n) / tenPow n
The round function is a little bit odd if you approach it from a non-mathematical point-of-view.
I would expect:
3.5 -> 4
4.3 -> 4
4.5 -> 5
4.8 -> 5
But Haskell, for good mathematical reasons, does this:
3.5 -> 4
4.3 -> 4
4.5 -> 4
4.8 -> 5
That is so round(3.5 + 4.5) = round 3.5 + round 4.5.
https://typeclasses.com/featured/rounding

Related

can you help me understand how this code working i am very starter in haskell

I am looking up some Haskell exercises with answers.
This is the exercise:
Assume that you have a function rainfall which computes the rainfall in your city for a given week (where weeks are numbered from 1 and upwards)
type WeekNumber = Int
rainfall :: WeekNumber -> Double -- assume this function exists
Complete the definition of the following function:
mostRain :: WeekNumber -> Double
mostRain n | n < 1 = 0
| otherwise = -- (complete this case)
Your solution must be recursive. Hint: The function max may be useful. Note that you do not have to provide a definition for the function rainfall.
The answer:
import Data.List
import Data.Maybe
import Test.QuickCheck
-- 1 ----------------
type WeekNumber = Int
rainfall :: WeekNumber -> Double
rainfall n = fromIntegral (n `mod` 7) * 3.9
mostRain :: WeekNumber -> Double
mostRain n | n < 1 = 0
| otherwise = rainfall n `max` mostRain (n - 1)
I really hoping that someone can help explain to me how they come up with this number 3.9 (n `mod` 7) * 3.9
and what actually happens here otherwise = rainfall n `max` mostRain (n - 1)?
First, as #AJFarmar points out, writing the rainfall function wasn't part of the exercise. The answer just provides an arbitrary definition so you can test the solution, and the number 3.9 was just pulled out of thin air to make the rainfall amounts seem "interesting":
> rainfall 1
3.9
> rainfall 2
7.8
>
You don't really need to understand what the expression:
fromIntegral (n `mod` 7) * 3.9
does to understand the solution, but if you're interested, it takes the input integer n, calculates n `mod` 7 (which is the remainder when n is divided by 7, so it turns 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 into 1, 2, 3, 4, 5, 6, 0, 1, 2, 3), and converts the result from an integer to a double before multiplying by 3.9. So, for example, this gives amounts of rainfall for weeks 1 to 10 that look like this:
> map rainfall [1..10]
[3.9,7.8,11.7,15.6,19.5,23.4,0.0,3.9,7.8,11.7]
>
To understand the part of the solution after otherwise, first let's rewrite it to get rid of the special backtick notation:
mostRain :: WeekNumber -> Double
mostRain n | n < 1 = 0
| otherwise = max (rainfall n) (mostRain (n - 1))
This definition says that the calculation of the most rain seen in weeks 1 to n, namely mostRain n, will be defined as 0 if n < 1 and by the following expression otherwise:
max (rainfall n) (mostRain (n - 1))
This expression evaluates the maximum of two numbers, the value of rainfall n (i.e., the rainfall in week n) and the value of mostRain (n - 1). This is a recursive call which will calculate the most rain seen in weeks 1 to n-1.
So, this is really saying that the most rain from weeks 1 to n is defined to be the maximum of (1) the amount of rain in week n and (2) the most rain seen in the previous weeks. Alternatively, you can think of it as performing a calculation in steps like this:
mostRain 3
= max (rainfall 3) (mostRain 2)
= max (rainfall 3) (max (rainfall 2) (mostRain 1))
= max (rainfall 3) (max (rainfall 2) (max (rainfall 1) (mostRain 0))
= max (rainfall 3) (max (rainfall 2) (max (rainfall 1) 0)
and if we fill in the simulated rainfall amounts, you can see how it ultimately calculates the maximum:
= max 11.7 (max 7.8 (max 3.9 0)
= max 11.7 (max 7.8 3.9)
= max 11.7 7.8
= 11.7
Notice that it says this in the description:
rainfall :: WeekNumber -> Double -- assume this function exists
That is to say, you're not actually expected to define rainfall. The definition they give in the solution is an example definition - the number 3.9 is entirely arbitrary. Ignore it.
You're only supposed to define mostRain, and so that's the part you should be paying attention to.

Sum of digits in recursion

Super-sum S of an integer x is defined as x if x is single digit number otherwise Super-sum of x is defined as Super-sum of digit-sum of x. Given two numbers n,k find the Super-sum of the number formed when n is concatenated k times.Note that k is only multiplied with the number when it is at least a 2 digit number
Input:
1987 4
Output:
1
Is there a faster method than this?
s,k=input().split()
summ=0
for ele in s:
summ+=int(ele)
s=summ*int(k)
while s>=10:
s=str(s)
summ=0
for ele in s:
summ+=int(ele)
s=summ
print(s)
n,k=map(int,input().split())
if n<10:
print(n)
else:
if ((n*k)%9==0):
print(9)
else:
res=(n*k)%9
Any number greater than 9 will have digits repeated that's why you need to take mod of 9 for example 13 will have sum of 1+3 =4 and 13 %9=4 .There will be a special case when mod of 9 will be zero and this will be at number 9,18,27,36 etc which are divisible by 9 and their sum will always be 9 hence return 9 .
The formula used in the accepted answer should actually be proved. So, let's do this.
First, let's prove that for any positive integer number N, N modulo 9 is the same sum of its digits modulo 9.
Having proved the statement above, we easily conclude that N % 9 provides the needed digit as per challenge description. The only exception is if N % 9 == 0, then a digit is 9.

Compare two numbers in Haskell [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
http://i.stack.imgur.com/71w9v.png
I have to find how much money a player wins.
This must be done by creating a function called digits Int->Int->Int. For example if the first input is 13758455 and the second input of the function is 13758455 then I should get 1000000 in the compiler.
This is normally an easy task in Java but I wasn't able to find something like a counter to count up as I find more digits in a number.
As there is no state in Haskell, you cannot have counters like you would in imperative languages.
You will often use recursion for this matter. Here is an example:
module Main where
moneyWon :: Int -> Int
moneyWon 8 = 1000000
moneyWon 7 = 100000
moneyWon 6 = 8000
moneyWon 5 = 300
moneyWon 4 = 20
moneyWon 3 = 5
moneyWon 2 = 1
moneyWon _ = 0
digits :: Int -> Int -> Int
digits 0 0 = 0
digits x y = digits dx dy + if mx == my then 1 else 0
where (dx, mx) = divMod x 10
(dy, my) = divMod y 10
main = do
print $ (moneyWon . digits 12345678) 12345668
Notes:
counting corresponding digits and evaluating the prize are two different concerns, that's why I've separated them
the divMod x 10 is a way to get the lowest meaning digit in base 10
in real life, you should not use an integer to hold the digits since it is more a list matter than a number matter (that's why the number starts at 10000000 and not at 0, forcing the user to enter the right number of digits).
Using Int leaves with the task to check the number is valid.

Need Hint for ProjectEuler Problem

What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
I could easily brute force the solution in an imperative programming language with loops. But I want to do this in Haskell and not having loops makes it much harder. I was thinking of doing something like this:
[n | n <- [1..], d <- [1..20], n `mod` d == 0] !! 0
But I know that won't work because "d" will make the condition equal True at d = 1. I need a hint on how to make it so that n mod d is calculated for [1..20] and can be verified for all 20 numbers.
Again, please don't give me a solution. Thanks.
As with many of the Project Euler problems, this is at least as much about math as it is about programming.
What you're looking for is the least common multiple of a set of numbers, which happen to be in a sequence starting at 1.
A likely tactic in a functional language is trying to make it recursive based on figuring out the relation between the smallest number divisible by all of [1..n] and the smallest number divisible by all of [1..n+1]. Play with this with some smaller numbers than 20 and try to understand the mathematical relation or perhaps discern a pattern.
Instead of a search until you find such a number, consider instead a constructive algorithm, where, given a set of numbers, you construct the smallest (or least) positive number that is evenly divisible by (aka "is a common multiple of") all those numbers. Look at the algorithms there, and consider how Euclid's algorithm (which they mention) might apply.
Can you think of any relationship between two numbers in terms of their greatest common divisor and their least common multiple? How about among a set of numbers?
If you look at it, it seems to be a list filtering operation. List of infinite numbers, to be filtered based on case the whether number is divisible by all numbers from 1 to 20.
So what we got is we need a function which takes a integer and a list of integer and tells whether it is divisible by all those numbers in the list
isDivisible :: [Int] -> Int -> Bool
and then use this in List filter as
filter (isDivisible [1..20]) [1..]
Now as Haskell is a lazy language, you just need to take the required number of items (in your case you need just one hence List.head method sounds good) from the above filter result.
I hope this helps you. This is a simple solution and there will be many other single line solutions for this too :)
Alternative answer: You can just take advantage of the lcm function provided in the Prelude.
For efficiently solving this, go with Don Roby's answer. If you just want a little hint on the brute force approach, translate what you wrote back into english and see how it differs from the problem description.
You wrote something like "filter the product of the positive naturals and the positive naturals from 1 to 20"
what you want is more like "filter the positive naturals by some function of the positive naturals from 1 to 20"
You have to get Mathy in this case. You are gonna do a foldl through [1..20], starting with an accumulator n = 1. For each number p of that list, you only proceed if p is a prime. Now for the previous prime p, you want to find the largest integer q such that p^q <= 20. Multiply n *= (p^q). Once the foldl finishes, n is the number you want.
A possible brute force implementation would be
head [n|n <- [1..], all ((==0).(n `mod`)) [1..20]]
but in this case it would take way too long. The all function tests if a predicate holds for all elements of a list. The lambda is short for (\d -> mod n d == 0).
So how could you speed up the calculation? Let's factorize our divisors in prime factors, and search for the highest power of every prime factor:
2 = 2
3 = 3
4 = 2^2
5 = 5
6 = 2 * 3
7 = 7
8 = 2^3
9 = 3^2
10 = 2 * 5
11 = 11
12 = 2^2*3
13 = 13
14 = 2 *7
15 = 3 * 5
16 = 2^4
17 = 17
18 = 2 * 3^2
19 = 19
20 = 2^2 * 5
--------------------------------
max= 2^4*3^2*5*7*11*13*17*19
Using this number we have:
all ((==0).(2^4*3^2*5*7*11*13*17*19 `mod`)) [1..20]
--True
Hey, it is divisible by all numbers from 1 to 20. Not very surprising. E.g. it is divisible by 15 because it "contains" the factors 3 and 5, and it is divisible by 16, because it "contains" the factor 2^4. But is it the smallest possible number? Think about it...

multiplicative inverse? [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I know that an affine cipher substitutes BD with SG. I need to find the encryption formula, in the form y = a x + b, where a and b are coefficients.
From the information above I end up having to equations:
a+b=18 and
3a+b=6
So I am working like this:
a+b=18 and 3a + b = 6-> 3a+18-a=6->  2a= 6-18 -> 2a=14 (as it is mod 26)
b=18-a
2a=? 
So, O want to multiply by the multiplicative inverse of 2 mod 26
I can't find a multiplicative inverse of number 2 with 26 (y = ax + b mod 26)
Can anyone please help me find a and b?
That's because 2 doesn't have a multiplicative inverse mod 26: since 13*2=0, there does not exist K such that K * a = 1. Your modulus must be prime. Try looking up the Chinese Remainder Theorem for more information.
To be more specific, integers mod 26 is not a field (a mathematical set where every element, except 0, has a multiplicative inverse). Any ring in which a * b = 0, for some a!=0 and b!=0, is not a field.
In fact, a field will always have p^n elements, where p is a prime number and n is a positive integer. The simplest fields are just integers mod a prime number, but for prime powers you need to construct a more elaborate system. So, in short, use a different modulus like 29.
Does a = 7 work? 2*7 = 14. Thus, b = 11.
Let's check the 2 equations to see if that works:
7+11 = 18 (check for the first equation).
3*7+11=21+11 = 32 = 6.
What is wrong with the above?
EDIT: Ok, now I see what could go wrong with trying to do a division by 2 in a non-prime modulus as it is similar to a division by 0. You could take ribond's suggestion of using the Chinese Remainder Theorem and split the equations into another pair of pairs:
mod 13: a+b=5, 3a+b=6. (2a = 1 = 14 => a=7. b = 18-7 = 11.)
mod 2: a+b=0. 3a+b=0 (Note this is the same equation and has a pair of possible solutions where a and b are either 0 or 1.)
Thus there is the unique solution for your problem I think.
Other posters are right in that there is no inverse of 2 modulo 26, so you can't solve 2a=14 mod 26 by multiplying through by the inverse of 2. But that doesn't mean that 2a=14 mod 26 isn't solvable.
Consider the general equation cx = d mod n (c=2,d=14,n=26 in your case). Let g = gcd(c,n). The equation cx=d has a solution if an only if g divides d. If g divides d, then there are in fact multiple solutions (g of them). The equation (c/g)x = d/g mod n/g has a unique solution (call it x_0) because c/g is relatively prime to n/g and therefore has an inverse. The solutions to the original equation are x_0, x_0 + n/g, ..., x_0 + (g-1)n/g.
In your case c=2,d=14,n=26, and g=2. g divides d, so first solve the equation (2/2)x = (14/2) mod (26/2) which gives 7. So both 7 and 7+13=20 solve your original equation.
Note that this means you haven't uniquely determined your affine transformation, two possibilities still exist. You need another data point...

Resources