user902691
user902691

Reputation: 1159

Numbers generation bad value

I would like to implementing Bernoulli numbers generation in Scala. I select this algorithm. I wrote following code:

def bernoulli(n: Int) = {

val a: Array[Fraction] = Array.fill(n + 1) {
  new Fraction()
}

for (m <- 0 to n) {

  a(m) = new Fraction(1, m + 1, 1 / (m + 1F))

  for (j <- m to 1 by -1) {

    val vc = a(j - 1)
    vc.value= j * (vc.value - a(j).value)
  }

}
a.head


 }

  class Fraction(var numerator: Int = 0, var denominator: Int = 0, var value: Float = 0)

But when I print bernoulli(5) it is not 0.

Upvotes: 0

Views: 67

Answers (1)

mohit
mohit

Reputation: 4999

The code that you are using seems to work fine. The reason that you don't get 0 is because of floating point errors. If you want more accurate results, you can use BigDecimal rather than floats.

To use BigDecimal, use a(m) = new Fraction(1, m + 1, 1 / BigDecimal(m + 1)) and use BigDecimal for the class.

By using BigDecimal, you will get

    bernoulli(5).value  //> res0: BigDecimal = -1.00E-32

which is close to 0.

Upvotes: 1

Related Questions