Unsure how a method works within a scala class - scala

I'm trying to understand the add method in below class taken from book 'Programming in Scala - Second Edition'.
Is this correct :
The method 'add' takes defines an operator which of type Rational. I don't know what is occurring within the new Rational :
numer * that.denom + that.numer * denom,
denom * that.denom
How are numer & denom be assigned here ? , Why is each expression separated by a comma ?
Entire class :
class Rational(n: Int , d: Int) {
require(d != 0)
private val g = gcd(n.abs, d.abs)
val numer = n / g
val denom = d/ g
def this(n: Int) = this(n, 1)
def add(that: Rational): Rational =
new Rational(
numer * that.denom + that.numer * denom,
denom * that.denom
)
override def toString = numer +"/" + denom
private def gcd(a: Int, b: Int): Int =
if(b == 0) a else gcd(b, a % b)
}

That two expressions are the arguments to the Rational constructor, thus they will be the private vals n and d respectively. For example
class C(a: Int, b: Int)
val c1 = new C(1, 2) // here 1, 2 is like the two expressions you mention
The add method implements rational number addition:
a c a*d c*b a*d + c*b
--- + --- = ----- + ----- = -----------
b d b*d b*d b*d
where
a = numer
b = denom
c = that.numer
d = that.denom

Related

How to create custom operators with precedence

I hava a class with custom Operators
case class Num(var value:Int) {
def add(x:Num) = Num(value + x.value)
def mul(x:Num) = Num(value * x.value)
}
So I can call them like this
val a = Num(2)
val b = Num(3)
val c = Num(4)
val m1 = a add b mul c
But how can I execute mul before add? I saw a solution like +| instead of add, but I want include letters in my Operator and +add and *mul not working. Also I want to include a pow function, so this needs an higher precidence than mul
You can use Parenthesis after add.
val m1 = a add (b mul c) = 14
val m1 = a add b mul c = 20
Update
you do not have any restrictions in naming your methods. For example, you can define methods +, -, * and etc. for a class.
case class Num(var value:Int) {
def + (x:Num) = Num(value + x.value)
def *(x:Num) = Num(value * x.value)
}
object Num extends App {
val a = Num(2)
val b = Num(3)
val c = Num(4)
val m1 = a + b * c
println(m1)
}
Output
Num(14)

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.

How to ceil the result for UInt division in Chisel

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}
}

Why does Breeze binomial distribution return NaN when it should return 1.0?

The following gives NaN, but should give 1.0, why?
breeze.stats.distributions.Binomial(10, 1.0).probabilityOf(10)
similarily for Binomial(1, 0.0).probabilityOf(0)
From the breeze source.
case class Binomial(n: Int, p: Double)(implicit rand: RandBasis=Rand) extends DiscreteDistr[Int] with Moments[Double, Double] {
require(n > 0, "n must be positive!");
require(p >= 0.0, "p must be non-negative!");
def probabilityOf(k: Int) = exp(logProbabilityOf(k));
override def toString() = "Binomial(" + n + ", " + p + ")";
override def logProbabilityOf(k: Int) = {
require(n >= k);
require(k >= 0);
lgamma(n+1) - lgamma(k+1) - lgamma(n-k+1) + k * log(p) + (n-k) * log(1-p)
}
The log of 0 is undefined. In your first example, you have p as 1 so the final log(1-p) = log(0) = undefined and in your second example, log(p) = log(0) = undefined
Since these probabilities both should have been 1, I think this is a bug in breeze source code

Rational code in scala

/* want to read the rational code which compute ((1/2)+(2/3)). I finde this code but I have one question about that*/
object Rationals
{
val x= new Rational(1, 2) // 1/2
x.numer // *
x.denom // **
/* * and ** are my questions. why I have to use them? */
val y = new Rational(2, 3) // 2/3
x.add(y)
/* my result most be equal to 7/6 */
}
class Rational (x : Int, y : Int)
{
def numer= x
def denom= y
def add (that : Rational) =
new Rational (
numer * that.denom + that.numer * denom, /* 1*3 + 2*2 */
denom * that.denom) /* 2*2 */
override def toString = numer + "/" + denom /* 7/6 */
}
The lines:
x.numer // *
x.denom // **
aren't doing anything. They are getting computed but not used; and they don't have side-effects.