How to ceil the result for UInt division in Chisel - scala

As the title stated, how to do that?
val a = 3.U
val result = a / 2.U
result would be 1.U
However I want to apply ceil on division.
val result = ceil(a / 2.U )
Therefore, I could get 2.U of the result value.

When dividing a by b, if you know that a is not too big (namely that a <= UInt.MaxValue - (b - 1)), then you can do
def ceilUIntDiv(a: UInt, b: UInt): UInt =
(a + b - 1.U) / b
If a is potentially too big, then the above can overflow, and you'll need to adapt the result after the fact instead:
def ceilUIntDiv(a: UInt, b: UInt): UInt = {
val c = a / b
if (b * c == a) c else c + 1.U
}

The problem is the expression a / 2.U is indeed 1.U: if you apply ceil to 1.U you'll get 1.U.
Recall that this happens to Ints as well, as they use integer division:
scala> val result = Math.ceil(3 / 2)
result: Double = 1.0
What you should do is to enforce one of the division operands to be a Double likewise:
scala> val result = Math.ceil(3 / (2: Double))
result: Double = 2.0
And then just convert it back to UInt.

def ceilUIntDiv(a: UInt, b: UInt): UInt = {
(a / b) + {if (a % b == 0.U) 0.U else 1.U}
}

Related

type mismatch in scala when using reduce

Can anybody help me understand what's wrong with the code below?
case class Point(x: Double, y: Double)
def centroid(points: IndexedSeq[Point]): Point = {
val x = points.reduce(_.x + _.x)
val y = points.reduce(_.y + _.y)
val len = points.length
Point(x/len, y/len)
}
I get the error when I run it:
Error:(10, 30) type mismatch;
found : Double
required: A$A145.this.Point
val x = points.reduce(_.x + _.x)
^
reduce, in this case, takes a function of type (Point, Point) => Point and returns a Point.
One way to calculate the centroid:
case class Point(x: Double, y: Double)
def centroid(points: IndexedSeq[Point]): Point = {
val x = points.map(_.x).sum
val y = points.map(_.y).sum
val len = points.length
Point(x/len, y/len)
}
If you want to use reduce you need to reduce both x and y in a single pass like this
def centroid(points: IndexedSeq[Point]): Point = {
val p = points.reduce( (s, p) => Point(s.x + p.x, s.y + p.y) )
val len = points.length
Point(p.x/len, p.y/len)
}
If you want to compute x and y independently then use foldLeft rather than reduce like this
def centroid(points: IndexedSeq[Point]): Point = {
val x = points.foldLeft(0.0)(_ + _.x)
val y = points.foldLeft(0.0)(_ + _.y)
val len = points.length
Point(x/len, y/len)
}
This is perhaps clearer but does process the points twice so it may be marginally less efficient.

Tail Recursive function for the sum of fractions

I am trying to convert this recursive function into a tail recursive function
def sumOfFractions(n: Int): Double = {
require(n > 0, "Parameter n has to be greater than 0");
if (n==1)
1.0
else
1.0 / n + sumOfFractions(n - 1)
}
I thought that this solution would work but when it runs it just returns 1.0
def sumOfFractions(n:Int):Double = {
def inner(acc:Int, n:Int): Double={
if(n <= 1)1.0
else
{
inner(acc+(1/n),n-1)
}
}
inner(0,n)
}
I think this is because the accumulator is not being updated correctly but I don't understand why. The code is in Scala but an example in any language would be helpful.
You need the base case (n <= 1) to return the accumulator, not 1.0. You'll also run into problems because the accumulator is an Int instead of a Double, which means that + (1 / n) is just adding 0 (the result of dividing 1: Int by any n: Int greater than one).
You can fix this by changing acc's type and making the numerator of the reciprocal a literal double:
def sumOfFractions(n: Int):Double = {
def inner(acc: Double, n: Int): Double =
if (n <= 1) acc else inner(acc + (1.0 / n), n - 1)
inner(0, n)
}
This should work.
Correct your code
1) Return acc (accumulator) when n <= 1
2) Your acc should be Double type
3) Division should be floating point division
def sumOfFractions(n: Int): Double = {
def inner(acc: Double, n:Int): Double = if(n <= 1) acc
else inner(acc + (1.0 / n), n - 1)
inner(0,n)
}
Using foldLeft
def sumOfFractions(n: Int): Double =
(1 to n).foldLeft(0.0)((r, c) => r + (1.0 / c))

How can I pad a Vector of Strings in Scala?

I'd like to pad a vector of strings with a given value on all sides (i.e., top, bottom, right, left). For example, the following vector of strings:
1122
1122
3344
3344
should look like this:
000000
011220
011220
033440
033440
000000
Of course, this representation is purely for visual purposes and it is actually a Vector of strings.
I found I can accomplish this with the following code.
val v = Vector("1122", "1122", "3344", "3344")
Vector("000000") ++ (for { r <- v } yield "0" + r + "0") ++ Vector("000000")
However, I am fairly new to Scala and I feel I might be missing a better way to accomplish this. Is there a better way to pad a Vector of Strings in Scala with a given value?
Using jwvh's map approach with the * operator on String:
def repeat(len: Int, c: Char) = c.toString * len
def padLeftRight(s: String, len: Int, c: Char) = {
repeat(len - 1 - s.size, c) + s + c
}
def padSeq[S <: Seq[String]](xs: S, c: Char) = {
val len = xs.map(_.size).max + 2
val padded = repeat(len, c)
padded +: xs.map(padLeftRight(_, len, c)) :+ padded
}
Using padSeq with your example:
val v = Vector("1122", "1122", "3344", "3344")
val result = padSeq(v, '0')
gives:
Vector("000000", "011220", "011220", "033440", "033440", "000000")

What is a good way of reusing function result in Scala

Let me clarify my question by example. This is a standard exponentiation algorithm written with tail recursion in Scala:
def power(x: Double, y: Int): Double = {
def sqr(z: Double): Double = z * z
def loop(xx: Double, yy: Int): Double =
if (yy == 0) xx
else if (yy % 2 == 0) sqr(loop(xx, yy / 2))
else loop(xx * x, yy - 1)
loop(1.0, y)
}
Here sqr method is used to produce the square of loop's result. It doesn't look like a good idea - to define a special function for such a simple operation. But, we can't write just loop(..) * loop(..) instead, since it doubles the calculations.
We also can write it with val and without sqr function:
def power(x: Double, y: Int): Double = {
def loop(xx: Double, yy: Int): Double =
if (yy == 0) xx
else if (yy % 2 == 0) { val s = loop(xx, yy / 2); s * s }
else loop(xx * x, yy - 1)
loop(1.0, y)
}
I can't say that it looks better then variant with sqr, since it uses state variable. The first case is more functional the second way is more Scala-friendly.
Anyway, my question is how to deal with cases when you need to postprocess function's result? Maybe Scala has some other ways to achieve that?
You are using the law that
x^(2n) = x^n * x^n
But this is the same as
x^n * x^n = (x*x)^n
Hence, to avoid squaring after recursion, the value in the case where y is even should be like displayed below in the code listing.
This way, tail-calling will be possible. Here is the full code (not knowing Scala, I hope I get the syntax right by analogy):
def power(x: Double, y: Int): Double = {
def loop(xx: Double, acc: Double, yy: Int): Double =
if (yy == 0) acc
else if (yy % 2 == 0) loop(xx*xx, acc, yy / 2)
else loop(xx, acc * xx, yy - 1)
loop(x, 1.0, y)
}
Here it is in a Haskell like language:
power2 x n = loop x 1 n
where
loop x a 0 = a
loop x a n = if odd n then loop x (a*x) (n-1)
else loop (x*x) a (n `quot` 2)
You could use a "forward pipe". I've got this idea from here: Cache an intermediate variable in an one-liner.
So
val s = loop(xx, yy / 2); s * s
could be rewritten to
loop(xx, yy / 2) |> (s => s * s)
using an implicit conversion like this
implicit class PipedObject[A](value: A) {
def |>[B](f: A => B): B = f(value)
}
As Petr has pointed out: Using an implicit value class
object PipedObjectContainer {
implicit class PipedObject[A](val value: A) extends AnyVal {
def |>[B](f: A => B): B = f(value)
}
}
to be used like this
import PipedObjectContainer._
loop(xx, yy / 2) |> (s => s * s)
is better, since it does not need a temporary instance (requires Scala >= 2.10).
In my comment I pointed out that your implementations can't be tail call optimised, because in the case where yy % 2 == 0, there is a recursive call that is not in tail position. So, for a large input, this can overflow the stack.
A general solution to this is to trampoline your function, replacing recursive calls with data which can be mapped over with "post-processing" such as sqr. The result is then computed by an interpreter, which steps through the return values, storing them on the heap rather than the stack.
The Scalaz library provides an implementation of the data types and interpreter.
import scalaz.Free.Trampoline, scalaz.Trampoline._
def sqr(z: Double): Double = z * z
def power(x: Double, y: Int): Double = {
def loop(xx: Double, yy: Int): Trampoline[Double] =
if (yy == 0)
done(xx)
else if (yy % 2 == 0)
suspend(loop(xx, yy / 2)) map sqr
else
suspend(loop(xx * x, yy - 1))
loop(1.0, y).run
}
There is a considerable performance hit for doing this, though. In this particular case, I would use Igno's solution to avoid the need to call sqr at all. But, the technique described above can be useful when you can't make such optimisations to your algorithm.
In this particular case
No need for utility functions
No need for obtuse piping / implicits
Only need a single standalone recursive call at end - to always give tail recursion
def power(x: Double, y: Int): Double =
if (y == 0) x
else {
val evenPower = y % 2 == 0
power(if (evenPower) x * x else x, if (evenPower) y / 2 else y - 1)
}

power and modulo on the fly for big numbers

I raise some basis b to the power p and take the modulo m of that.
Let's assume b=55170 or 55172 and m=3043839241 (which happens to be the square of 55171). The linux-calculator bc gives the results (we need this for control):
echo "p=5606;b=55171;m=b*b;((b-1)^p)%m;((b+1)^p)%m" | bc
2734550616
309288627
Now calculating 55170^5606 gives a somewhat large number, but since I have to do a modulooperation, I can circumvent the usage of BigInt, I thought, because of:
(a*b) % c == ((a%c) * (b%c))%c i.e.
(9*7) % 5 == ((9%5) * (7%5))%5 =>
63 % 5 == (4 * 2) %5 =>
3 == 8 % 5
... and a^d = a^(b+c) = a^b * a^c, therefore I can divide b+c by 2, which gives, for even or odd ds d/2 and d-(d/2), so for 8^5 I can calculate 8^2 * 8^3.
So my (defective) method, which always cut's off the divisor on the fly looks like that:
def powMod (b: Long, pot: Int, mod: Long) : Long = {
if (pot == 1) b % mod else {
val pot2 = pot/2
val pm1 = powMod (b, pot2, mod)
val pm2 = powMod (b, pot-pot2, mod)
(pm1 * pm2) % mod
}
}
and feeded with some values,
powMod (55170, 5606, 3043839241L)
res2: Long = 1885539617
powMod (55172, 5606, 3043839241L)
res4: Long = 309288627
As we can see, the second result is exactly the same as the one above, but the first one looks quiet different. I'm doing a lot of such calculations, and they seem to be accurate as long as they stay in the range of Int, but I can't see any error. Using a BigInt works as well, but is way too slow:
def calc2 (n: Int, pri: Long) = {
val p: BigInt = pri
val p3 = p * p
val p1 = (p-1).pow (n) % (p3)
val p2 = (p+1).pow (n) % (p3)
print ("p1: " + p1 + " p2: " + p2)
}
calc2 (5606, 55171)
p1: 2734550616 p2: 309288627
(same result as with bc) Can somebody see the error in powMod?
I think the answer is here:
scala> math.sqrt(Long.MaxValue).toLong < 3043839241L
res9: Boolean = true
That means you can have a long overflow even for numbers which are less than that particular module value. Let's try to catch it:
scala> def powMod (b: Long, pot: Int, mod: Long) : Long = {
| if (pot == 1) b % mod else {
| val pot2 = pot/2
| val pm1 = powMod (b, pot2, mod)
| val pm2 = powMod (b, pot-pot2, mod)
| val partial = ((pm1 % mod) * (pm2 % mod)).ensuring(res =>
| res > pm1 % mod && res > pm2 % mod, "Long overflow multiplying "+pm1+" by "+pm2)
| partial % mod
| }
| }
powMod: (b: Long,pot: Int,mod: Long)Long
scala> powMod (55170, 5606, 3043839241L)
java.lang.AssertionError: assertion failed: Long overflow multiplying 3042625480 by 3042625480
There you have it.
Not familiar with Scala, but...
def powMod (b: Long, pot: Int, mod: Long) : Long = {
if (pot == 1) b % mod else {
val pot2 = pot/2
val pm1 = powMod (b, pot, mod)
val pm2 = powMod (b, pot-pot2, mod)
(pm1 * pm2) % mod
}
}
Did you mean
val pm1 = powMod (b, pot2, mod)
Notice the pot2 instead of pot.
Strangely, it seems that this should loop forever/overflow the stack, but who knows what Scala is doing.
Ok fellows, it took me some time, and finally destroyed a long but never proven assumption, which was, that if you multiply two 64-bit-positive integral values (aka: Longs, and practically only 63-bit, after all), you could overrun, and get negative values, but not get an overrun to reach positive (but wrong) values again.
So I had tried to put a guard into my code, to calculate my value with BigInt, it too big, but the guard was insufficient, because I tested for res < 0. res < pm1 && res < pm2 isn't sufficient too.
To increase the speed I used a mutable.HashMap, and now the code looks like this:
val MVL : Long = Integer.MAX_VALUE
var modPow = new scala.collection.mutable.HashMap [(Long, Int, Long), Long ] ()
def powMod (b: Long, pot: Int, mod: Long) : Long = {
if (pot == 1) b % mod else modPow.getOrElseUpdate ((b, pot, mod), {
val pot2= pot/2
val pm1 = powMod (b, pot2, mod)
val pm2 = powMod (b, pot-pot2, mod)
val res = (pm1 * pm2)
// avoid Long-overrun
if (pm1 < MVL && pm2 < MVL)
res % mod else {
val f1: BigInt = pm1
val f2: BigInt = pm2
val erg = (f1 * f2) % mod
erg.longValue
}
})
}
You might ask yourself, whether the Long-declared MVL is really needed, or whether a
if (pm1 < Integer.MAX_VALUE && ...
would have worked too. No. It wouldn't. :) Another trap to avoid. :)
Finally it is pretty fast and correct and I learned two lessons about overruns and MAX_VALUE - comparision.