package math
The package object scala.math contains methods for performing basic
numeric operations such as elementary exponential, logarithmic, root and
trigonometric functions.
All methods forward to java.lang.Math unless otherwise noted.
- Source
- package.scala
- See also
- Grouped
- Alphabetic
- By Inheritance
- math
- AnyRef
- Any
- Hide All
- Show All
- Public
- Protected
Type Members
- final class BigDecimal extends ScalaNumber with ScalaNumericConversions with Serializable with Ordered[BigDecimal]
BigDecimalrepresents decimal floating-point numbers of arbitrary precision.BigDecimalrepresents decimal floating-point numbers of arbitrary precision. By default, the precision approximately matches that of IEEE 128-bit floating point numbers (34 decimal digits,HALF_EVENrounding mode). Within the range of IEEE binary128 numbers,BigDecimalwill agree withBigIntfor both equality and hash codes (and will agree with primitive types as well). Beyond that range--numbers with more than 4934 digits when written out in full--thehashCodeofBigIntandBigDecimalis allowed to diverge due to difficulty in efficiently computing both the decimal representation inBigDecimaland the binary representation inBigInt.When creating a
BigDecimalfrom aDoubleorFloat, care must be taken as the binary fraction representation ofDoubleandFloatdoes not easily convert into a decimal representation. Three explicit schemes are available for conversion.BigDecimal.decimalwill convert the floating-point number to a decimal text representation, and build aBigDecimalbased on that.BigDecimal.binarywill expand the binary fraction to the requested or default precision.BigDecimal.exactwill expand the binary fraction to the full number of digits, thus producing the exact decimal value corresponding to the binary fraction of that floating-point number.BigDecimalequality matches the decimal expansion ofDouble:BigDecimal.decimal(0.1) == 0.1. Note that since0.1f != 0.1, the same is not true forFloat. Instead,0.1f == BigDecimal.decimal((0.1f).toDouble).To test whether a
BigDecimalnumber can be converted to aDoubleorFloatand then back without loss of information by using one of these methods, test withisDecimalDouble,isBinaryDouble, orisExactDoubleor the correspondingFloatversions. Note thatBigInt'sisValidDoublewill agree withisExactDouble, not theisDecimalDoubleused by default.BigDecimaluses the decimal representation of binary floating-point numbers to determine equality and hash codes. This yields different answers than conversion betweenLongandDoublevalues, where the exact form is used. As always, since floating-point is a lossy representation, it is advisable to take care when assuming identity will be maintained across multiple conversions.BigDecimalmaintains aMathContextthat determines the rounding that is applied to certain calculations. In most cases, the value of theBigDecimalis also rounded to the precision specified by theMathContext. To create aBigDecimalwith a different precision than itsMathContext, usenew BigDecimal(new java.math.BigDecimal(...), mc). Rounding will be applied on those mathematical operations that can dramatically change the number of digits in a full representation, namely multiplication, division, and powers. The left-hand argument'sMathContextalways determines the degree of rounding, if any, and is the one propagated through arithmetic operations that do not apply rounding themselves. - final class BigInt extends ScalaNumber with ScalaNumericConversions with Serializable with Ordered[BigInt]
A type with efficient encoding of arbitrary integers.
A type with efficient encoding of arbitrary integers.
It wraps
java.math.BigInteger, with optimization for small values that can be encoded in aLong. - trait Equiv[T] extends Serializable
A trait for representing equivalence relations.
A trait for representing equivalence relations. It is important to distinguish between a type that can be compared for equality or equivalence and a representation of equivalence on some type. This trait is for representing the latter.
An equivalence relation is a binary relation on a type. This relation is exposed as the
equivmethod of theEquivtrait. The relation must be:- reflexive:
equiv(x, x) == truefor any x of typeT. - symmetric:
equiv(x, y) == equiv(y, x)for anyxandyof typeT. - transitive: if
equiv(x, y) == trueandequiv(y, z) == true, thenequiv(x, z) == truefor anyx,y, andzof typeT.
- reflexive:
- trait Fractional[T] extends Numeric[T]
- trait Integral[T] extends Numeric[T]
- trait LowPriorityEquiv extends AnyRef
- trait LowPriorityOrderingImplicits extends AnyRef
- trait Numeric[T] extends Ordering[T]
- trait Ordered[A] extends Comparable[A]
A trait for data that have a single, natural ordering.
A trait for data that have a single, natural ordering. See scala.math.Ordering before using this trait for more information about whether to use scala.math.Ordering instead.
Classes that implement this trait can be sorted with scala.util.Sorting and can be compared with standard comparison operators (e.g. > and <).
Ordered should be used for data with a single, natural ordering (like integers) while Ordering allows for multiple ordering implementations. An Ordering instance will be implicitly created if necessary.
scala.math.Ordering is an alternative to this trait that allows multiple orderings to be defined for the same type.
scala.math.PartiallyOrdered is an alternative to this trait for partially ordered data.
For example, create a simple class that implements
Orderedand then sort it with scala.util.Sorting:case class OrderedClass(n:Int) extends Ordered[OrderedClass] { def compare(that: OrderedClass) = this.n - that.n } val x = Array(OrderedClass(1), OrderedClass(5), OrderedClass(3)) scala.util.Sorting.quickSort(x) x
It is important that the
equalsmethod for an instance ofOrdered[A]be consistent with the compare method. However, due to limitations inherent in the type erasure semantics, there is no reasonable way to provide a default implementation of equality for instances ofOrdered[A]. Therefore, if you need to be able to use equality on an instance ofOrdered[A]you must provide it yourself either when inheriting or instantiating.It is important that the
hashCodemethod for an instance ofOrdered[A]be consistent with thecomparemethod. However, it is not possible to provide a sensible default implementation. Therefore, if you need to be able compute the hash of an instance ofOrdered[A]you must provide it yourself either when inheriting or instantiating. - trait Ordering[T] extends Comparator[T] with PartialOrdering[T] with Serializable
Ordering is a trait whose instances each represent a strategy for sorting instances of a type.
Ordering is a trait whose instances each represent a strategy for sorting instances of a type.
Ordering's companion object defines many implicit objects to deal with subtypes of AnyVal (e.g.
Int,Double),String, and others.To sort instances by one or more member variables, you can take advantage of these built-in orderings using Ordering.by and Ordering.on:
import scala.util.Sorting val pairs = Array(("a", 5, 2), ("c", 3, 1), ("b", 1, 3)) // sort by 2nd element Sorting.quickSort(pairs)(Ordering.by[(String, Int, Int), Int](_._2)) // sort by the 3rd element, then 1st Sorting.quickSort(pairs)(Ordering[(Int, String)].on(x => (x._3, x._1)))
An
Ordering[T]is implemented by specifying the compare method,compare(a: T, b: T): Int, which decides how to order two instancesaandb. Instances ofOrdering[T]can be used by things likescala.util.Sortingto sort collections likeArray[T].For example:
import scala.util.Sorting case class Person(name:String, age:Int) val people = Array(Person("bob", 30), Person("ann", 32), Person("carl", 19)) // sort by age object AgeOrdering extends Ordering[Person] { def compare(a:Person, b:Person) = a.age.compare(b.age) } Sorting.quickSort(people)(AgeOrdering)
This trait and scala.math.Ordered both provide this same functionality, but in different ways. A type
Tcan be given a single way to order itself by extendingOrdered. UsingOrdering, this same type may be sorted in many other ways.OrderedandOrderingboth provide implicits allowing them to be used interchangeably.You can
import scala.math.Ordering.Implicits._to gain access to other implicit orderings.- Annotations
- @implicitNotFound()
- See also
scala.math.Ordered, scala.util.Sorting, scala.math.Ordering.Implicits
- trait PartialOrdering[T] extends Equiv[T]
A trait for representing partial orderings.
A trait for representing partial orderings. It is important to distinguish between a type that has a partial order and a representation of partial ordering on some type. This trait is for representing the latter.
A partial ordering is a binary relation on a type
T, exposed as thelteqmethod of this trait. This relation must be:- reflexive:
lteq(x, x) == true, for anyxof typeT. - anti-symmetric: if
lteq(x, y) == trueandlteq(y, x) == truethenequiv(x, y) == true, for anyxandyof typeT. - transitive: if
lteq(x, y) == trueandlteq(y, z) == truethenlteq(x, z) == true, for anyx,y, andzof typeT.
Additionally, a partial ordering induces an equivalence relation on a type
T:xandyof typeTare equivalent if and only iflteq(x, y) && lteq(y, x) == true. This equivalence relation is exposed as theequivmethod, inherited from the Equiv trait. - reflexive:
- trait PartiallyOrdered[+A] extends Any
A class for partially ordered data.
- trait ScalaNumericAnyConversions extends Any
Conversions which present a consistent conversion interface across all the numeric types, suitable for use in value classes.
- trait ScalaNumericConversions extends ScalaNumber with ScalaNumericAnyConversions
A slightly more specific conversion trait for classes which extend ScalaNumber (which excludes value classes.)
Value Members
- final val E: Double(2.718281828459045)
The
Doublevalue that is closer than any other toe, the base of the natural logarithms. - def IEEEremainder(x: Double, y: Double): Double
- final val Pi: Double(3.141592653589793)
The
Doublevalue that is closer than any other topi, the ratio of the circumference of a circle to its diameter. - def abs(x: Double): Double
- def abs(x: Float): Float
- def abs(x: Long): Long
- def abs(x: Int): Int
- def acos(x: Double): Double
- def addExact(x: Long, y: Long): Long
- def addExact(x: Int, y: Int): Int
- def asin(x: Double): Double
- def atan(x: Double): Double
- def atan2(y: Double, x: Double): Double
Converts rectangular coordinates
(x, y)to polar(r, theta).Converts rectangular coordinates
(x, y)to polar(r, theta).- y
the abscissa coordinate
- x
the ordinate coordinate
- returns
the theta component of the point
(r, theta)in polar coordinates that corresponds to the point(x, y)in Cartesian coordinates.
- def cbrt(x: Double): Double
Returns the cube root of the given
Doublevalue.Returns the cube root of the given
Doublevalue.- x
the number to take the cube root of
- returns
the value ∛x
- def ceil(x: Double): Double
- def copySign(magnitude: Float, sign: Float): Float
- def copySign(magnitude: Double, sign: Double): Double
- def cos(x: Double): Double
- def cosh(x: Double): Double
Returns the hyperbolic cosine of the given
Doublevalue. - def decrementExact(x: Long): Long
- def decrementExact(x: Int): Int
- def exp(x: Double): Double
Returns Euler's number
eraised to the power of aDoublevalue.Returns Euler's number
eraised to the power of aDoublevalue.- x
the exponent to raise
eto.- returns
the value
ea, whereeis the base of the natural logarithms.
- def expm1(x: Double): Double
Returns
exp(x) - 1. - def floor(x: Double): Double
- def floorDiv(x: Long, y: Long): Long
- def floorDiv(x: Int, y: Int): Int
- def floorMod(x: Long, y: Long): Long
- def floorMod(x: Int, y: Int): Int
- def getExponent(d: Double): Int
- def getExponent(f: Float): Int
- def hypot(x: Double, y: Double): Double
Returns the square root of the sum of the squares of both given
Doublevalues without intermediate underflow or overflow.Returns the square root of the sum of the squares of both given
Doublevalues without intermediate underflow or overflow.The r component of the point
(r, theta)in polar coordinates that corresponds to the point(x, y)in Cartesian coordinates. - def incrementExact(x: Long): Long
- def incrementExact(x: Int): Int
- def log(x: Double): Double
Returns the natural logarithm of a
Doublevalue.Returns the natural logarithm of a
Doublevalue.- x
the number to take the natural logarithm of
- returns
the value
logₑ(x)whereeis Eulers number
- def log10(x: Double): Double
Returns the base 10 logarithm of the given
Doublevalue. - def log1p(x: Double): Double
Returns the natural logarithm of the sum of the given
Doublevalue and 1. - def max(x: Double, y: Double): Double
- def max(x: Float, y: Float): Float
- def max(x: Long, y: Long): Long
- def max(x: Int, y: Int): Int
- def min(x: Double, y: Double): Double
- def min(x: Float, y: Float): Float
- def min(x: Long, y: Long): Long
- def min(x: Int, y: Int): Int
- def multiplyExact(x: Long, y: Long): Long
- def multiplyExact(x: Int, y: Int): Int
- def negateExact(x: Long): Long
- def negateExact(x: Int): Int
- def nextAfter(start: Float, direction: Double): Float
- def nextAfter(start: Double, direction: Double): Double
- def nextDown(f: Float): Float
- def nextDown(d: Double): Double
- def nextUp(f: Float): Float
- def nextUp(d: Double): Double
- def pow(x: Double, y: Double): Double
Returns the value of the first argument raised to the power of the second argument.
Returns the value of the first argument raised to the power of the second argument.
- x
the base.
- y
the exponent.
- returns
the value
xy.
- def random(): Double
Returns a
Doublevalue with a positive sign, greater than or equal to0.0and less than1.0. - def rint(x: Double): Double
Returns the
Doublevalue that is closest in value to the argument and is equal to a mathematical integer.Returns the
Doublevalue that is closest in value to the argument and is equal to a mathematical integer.- x
a
Doublevalue- returns
the closest floating-point value to a that is equal to a mathematical integer.
- def round(x: Double): Long
Returns the closest
Longto the argument.Returns the closest
Longto the argument.- x
a floating-point value to be rounded to a
Long.- returns
the value of the argument rounded to the nearest
longvalue.
- def round(x: Float): Int
Returns the closest
Intto the argument.Returns the closest
Intto the argument.- x
a floating-point value to be rounded to a
Int.- returns
the value of the argument rounded to the nearest
Intvalue.
- def scalb(f: Float, scaleFactor: Int): Float
- def scalb(d: Double, scaleFactor: Int): Double
- def signum(x: Double): Double
- def signum(x: Float): Float
- def signum(x: Long): Long
- Note
Forwards to java.lang.Long
- def signum(x: Int): Int
- Note
Forwards to java.lang.Integer
- def sin(x: Double): Double
- def sinh(x: Double): Double
Returns the hyperbolic sine of the given
Doublevalue. - def sqrt(x: Double): Double
Returns the square root of a
Doublevalue.Returns the square root of a
Doublevalue.- x
the number to take the square root of
- returns
the value √x
- def subtractExact(x: Long, y: Long): Long
- def subtractExact(x: Int, y: Int): Int
- def tan(x: Double): Double
- def tanh(x: Double): Double
Returns the hyperbolic tangent of the given
Doublevalue. - def toDegrees(x: Double): Double
Converts an angle measured in radians to an approximately equivalent angle measured in degrees.
Converts an angle measured in radians to an approximately equivalent angle measured in degrees.
- x
angle, in radians
- returns
the measurement of the angle
xin degrees.
- def toIntExact(x: Long): Int
- def toRadians(x: Double): Double
Converts an angle measured in degrees to an approximately equivalent angle measured in radians.
Converts an angle measured in degrees to an approximately equivalent angle measured in radians.
- x
an angle, in degrees
- returns
the measurement of the angle
xin radians.
- def ulp(x: Float): Float
Returns the size of an ulp of the given
Floatvalue. - def ulp(x: Double): Double
Returns the size of an ulp of the given
Doublevalue. - object BigDecimal extends java.io.Serializable
- object BigInt extends java.io.Serializable
- object Equiv extends LowPriorityEquiv with java.io.Serializable
- object Fractional extends java.io.Serializable
- object Integral extends java.io.Serializable
- object Numeric extends java.io.Serializable
- object Ordered
- object Ordering extends LowPriorityOrderingImplicits with java.io.Serializable
This is the companion object for the scala.math.Ordering trait.
This is the companion object for the scala.math.Ordering trait.
It contains many implicit orderings as well as well as methods to construct new orderings.
- object PartialOrdering extends java.io.Serializable
Deprecated Value Members
- def round(x: Long): Long
There is no reason to round a
Long, but this method prevents unintended conversion toFloatfollowed by rounding toInt.There is no reason to round a
Long, but this method prevents unintended conversion toFloatfollowed by rounding toInt.- Annotations
- @deprecated
- Deprecated
(Since version 2.11.0) This is an integer type; there is no reason to round it. Perhaps you meant to call this with a floating-point value?
- Note
Does not forward to java.lang.Math
Mathematical Constants
Minimum and Maximum
Find the min or max of two numbers. Note: scala.collection.IterableOnceOps has min and max methods which determine the min or max of a collection.
Rounding
Scaling
Scaling with rounding guarantees
Exponential and Logarithmic
Trigonometric
Arguments in radians
Angular Measurement Conversion
Hyperbolic
Absolute Values
Determine the magnitude of a value by discarding the sign. Results are >= 0.
Signs
For signum extract the sign of a value. Results are -1, 0 or 1.
Note the signum methods are not pure forwarders to the Java versions.
In particular, the return type of java.lang.Long.signum is Int,
but here it is widened to Long so that each overloaded variant
will return the same numeric type it is passed.
Root Extraction
Polar Coordinates
Unit of Least Precision
Pseudo Random Number Generation
Exact Arithmetic
Integral addition, multiplication, stepping and conversion throwing ArithmeticException instead of underflowing or overflowing
Modulus and Quotient
Calculate quotient values by rounding to negative infinity
This is the documentation for the Scala standard library.
Package structure
The scala package contains core types like
Int,Float,ArrayorOptionwhich are accessible in all Scala compilation units without explicit qualification or imports.Notable packages include:
scala.collectionand its sub-packages contain Scala's collections frameworkscala.collection.immutable- Immutable, sequential data-structures such asVector,List,Range,HashMaporHashSetscala.collection.mutable- Mutable, sequential data-structures such asArrayBuffer,StringBuilder,HashMaporHashSetscala.collection.concurrent- Mutable, concurrent data-structures such asTrieMapscala.concurrent- Primitives for concurrent programming such asFuturesandPromisesscala.io- Input and output operationsscala.math- Basic math functions and additional numeric types likeBigIntandBigDecimalscala.sys- Interaction with other processes and the operating systemscala.util.matching- Regular expressionsOther packages exist. See the complete list on the right.
Additional parts of the standard library are shipped as separate libraries. These include:
scala.reflect- Scala's reflection API (scala-reflect.jar)scala.xml- XML parsing, manipulation, and serialization (scala-xml.jar)scala.collection.parallel- Parallel collections (scala-parallel-collections.jar)scala.util.parsing- Parser combinators (scala-parser-combinators.jar)scala.swing- A convenient wrapper around Java's GUI framework called Swing (scala-swing.jar)Automatic imports
Identifiers in the scala package and the
scala.Predefobject are always in scope by default.Some of these identifiers are type aliases provided as shortcuts to commonly used classes. For example,
Listis an alias forscala.collection.immutable.List.Other aliases refer to classes provided by the underlying platform. For example, on the JVM,
Stringis an alias forjava.lang.String.