2

Is there a way to create a new data type where I define the number of bits and arithmetic rules in Scala? I have a program that uses 32 bit floats but am trying to study how will affect the results.

I want to rewrite the program to do addition and multiplication on fixed point (d.f) numbers and return fixed point numbers of the same precision (d.f and not d1+d2.f1+f2). Furthermore, I want to have saturation so that when there is overflow, the result sticks to the maxed value rather than wrapping around. I also want to truncate bits if there is underflow.

From what I understand, the only 8 bit number is a short, and the only decimal numbers are floats and doubles. Can I somehow define this data type in Scala, or is the only way to do regular float arithmetic and round to the nearest number that can be represented by my desired type?

Thanks

yǝsʞǝla
  • 16,272
  • 2
  • 44
  • 65

2 Answers2

1

You would be limited by what types your JVM provides and supports unless you go and hack the JVM, or compile Scala to native code with some custom compiler settings.

More reasonable approach to achieve this would be to store your numbers as fractions. There are some libraries like Spire that let you do that. With Spire you can also chose Double or Rational speed/precision trade off.

yǝsʞǝla
  • 16,272
  • 2
  • 44
  • 65
1

You can't really define a primitive data type. But in Scala you can define a value class, e.g. class FixedPoint(x: Long) extends AnyVal. At the runtime it will in most cases (but not always!) be represented just as a Long.

While Spire, mentioned in the other answer, has a FixedPoint type, it says:

This value class uses a Long with an implicit denominator. The type itself doesn't contain information about the denominator. Instead, an implicit FixedScale instance is required to provide that context when necessary (for instance, during multiplication). Like the previous unsigned values, fixed point values will not be boxed in most cases.

This type is designed to solve a specific type of problem and should only be used in situations where a large number of rational numbers with the same denominator are needed, and efficiency is very important.

I also don't think its operations are saturated (though I am not certain).

Community
  • 1
  • 1
Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487