本文整理汇总了Scala中scala.math.pow类的典型用法代码示例。如果您正苦于以下问题:Scala pow类的具体用法?Scala pow怎么用?Scala pow使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了pow类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: PointSegmentMapper
//设置package包名称以及导入依赖的类
package pl.chelm.pwsz.congenial_giggle
import scala.math.signum
import scala.math.pow
class PointSegmentMapper {
def resolve(point: Point): Segment = {
var code: Int = 0;
0 until point.length foreach {
(index) =>
{
val position = pow(10, index).toInt
val a = point(index)
if (signum(a) >= 0) {
code = code + position
}
}
}
Segment(code)
}
}
object PointSegmentMapper {
def apply(): PointSegmentMapper = new PointSegmentMapper()
}
示例2: ConfusionMatrix
//设置package包名称以及导入依赖的类
import scala.math.pow
class ConfusionMatrix(targets: List[String]) {
// Var holding the mapping from attributes name to confusion matrix index
val indexMapping: Map[String, Int] = targets.view.zipWithIndex.toMap
// Actual confusion matrix
val matrix = Array.ofDim[Double](indexMapping.size, indexMapping.size)
// Cached values to avoid traversing the matrix each time we need the precision
var correctPredicted: Double = 0
var totalPredictions: Double = 0
def getAccuracy(): Double = {
correctPredicted / totalPredictions // return accuracy
}
override def toString: String = {
var string = "\nCONFUSION MATRIX\nPredicted \t Truth \n"
for(i <- 0 until pow(matrix.length,2).toInt) {
string += targets(i / matrix.length) + " - " + targets(i % matrix.length) + ": " + matrix(i / matrix.length)(i % matrix.length).toInt + "\n"
}
string += "Accuracy: " + (correctPredicted / totalPredictions) + "\n"
var jointSensitivity: Double = .0
for( i <- matrix.indices){
string += ("Sensitivity (" + targets(i) + "): ")
var trueLabeled: Double = 0
for (j <- matrix.indices){
trueLabeled += matrix(j)(i)
}
string += matrix(i)(i)/trueLabeled + "\n"
jointSensitivity += matrix(i)(i)/trueLabeled
}
string += "Mean Sensitivity: " + jointSensitivity/matrix.length + "\n"
var jointPrecision: Double = .0
for( i <- matrix.indices){
string += "Precision (" + targets(i) + "): "
var truePredicted: Double = 0
for (j <- matrix.indices){
truePredicted += matrix(i)(j)
}
string += matrix(i)(i)/truePredicted + "\n"
jointPrecision += matrix(i)(i)/truePredicted
}
string += "Mean Precision: " + jointPrecision/matrix.length + "\n"
string // return string
}
}
示例3: VectorUtils
//设置package包名称以及导入依赖的类
package com.lljv.analytics.analyzerengine
import scala.math.pow
import scala.math.sqrt
object VectorUtils {
def arrayNorm(array: Array[Double]): Double = {
val arraySquared = array.map(pow(_, 2))
val norm = sqrt(arraySquared.toSeq.sum)
return norm
}
def arrayNorm(array: Array[Float]): Float = {
val arrayDouble = array.map(_.toDouble)
return arrayNorm(arrayDouble).toFloat
}
def normalizeVector(vector: Array[Double]): Array[Double] = {
var normalizedVector: Array[Double] = vector
val vectorNorm = arrayNorm(normalizedVector)
if (vectorNorm > 1e-7) normalizedVector.map(_ / vectorNorm)
return normalizedVector
}
def normalizeVector(array: Array[Float]): Array[Float] = {
val arrayDouble: Array[Double] = array.map(_.toDouble)
return normalizeVector(arrayDouble).map(_.toFloat)
}
}
示例4: Optimization
//设置package包名称以及导入依赖的类
import breeze.linalg._
import scala.math.{pow}
import breeze.optimize._
object Optimization {
val fn = new DiffFunction[DenseVector[Double]] {
def calculate(x: DenseVector[Double]) = {
(pow(x(0) + 1.0, 2.0) +
pow(x(1) - 2.0, 2.0) +
pow(x(2) + 4.0, 2.0),
DenseVector(2.0 * (x(0) + 1),
2.0 * (x(1) - 2.0),
2.0 * (x(2) + 4.0)))
}
}
def main(args: Array[String]) {
val lbfgs = new LBFGS[DenseVector[Double]](maxIter=100,
m=10, tolerance=0.001)
val solution = lbfgs.minimize(fn, DenseVector(0.0, 0.0, 0.0))
println(solution)
}
}
示例5: Optimization
//设置package包名称以及导入依赖的类
import breeze.linalg._
import scala.math.{pow}
import breeze.optimize._
object Optimization {
val fn = new DiffFunction[DenseVector[Double]] {
def calculate(x: DenseVector[Double]) = {
(pow(x(0) + 1.0, 2.0) +
pow(x(1) - 2.0, 2.0) +
pow(x(2) + 4.0, 2.0),
DenseVector(2.0 * (x(0) + 1),
2.0 * (x(1) - 2.0),
2.0 * (x(2) + 4.0)))
}
}
def main(args: Array[String]) {
val minimum = DenseVector(-1.0, 2.0, -4.0)
println(fn.valueAt(minimum))
println(fn.gradientAt(minimum))
println(fn.calculate(minimum))
}
}
示例6: SortedBlocks
//设置package包名称以及导入依赖的类
package de.fuberlin.wiwiss.silk.execution.methods
import de.fuberlin.wiwiss.silk.entity.{Path, Index, Entity}
import de.fuberlin.wiwiss.silk.linkagerule.LinkageRule
import de.fuberlin.wiwiss.silk.execution.ExecutionMethod
import scala.math.{min,max,pow}
case class SortedBlocks(sourceKey: Path, targetKey: Path, overlap: Double = 0.5) extends ExecutionMethod {
private val minChar = 'a'
private val maxChar = 'z'
private val numChars = 3 //Maximum number of chars that will be indexed
private val blockCount = pow((maxChar - minChar + 1), 2).toInt
override def indexEntity(entity: Entity, rule: LinkageRule): Index = {
val key = if(sourceKey.variable == entity.desc.variable) sourceKey else targetKey
val values = entity.evaluate(key)
values.map(indexValue).reduce(_ merge _)
}
private def indexValue(value: String): Index = {
//Given a string, generate a value in the interval [0,1[
var index = 0.0
for(i <- 0 until min(numChars, value.length)) {
//Make sure the character is inside the interval [minChar,maxChar]
val croppedChar = min(max(value(i).toLower, minChar), maxChar)
//Update index
index += (croppedChar - minChar) / pow(maxChar - minChar + 1, i + 1)
}
//Generate index
Index.continuous(
value = index,
minValue = 0.0,
maxValue = 1.0,
blockCount = blockCount,
overlap = overlap
)
}
}
示例7: Maths
//设置package包名称以及导入依赖的类
package lila.common
import scala.annotation._
import scala.math.{ pow, sqrt }
import scalaz.NonEmptyList
object Maths {
def variance[T](a: NonEmptyList[T])(implicit n: Numeric[T]): Double = {
val m = mean(a)
a.map(i => pow(n.toDouble(i) - m, 2)).list.sum / a.size
}
def deviation[T](a: NonEmptyList[T])(implicit n: Numeric[T]): Double = sqrt(variance(a))
// ridiculously performance optimized mean function
def mean[T](a: NonEmptyList[T])(implicit n: Numeric[T]): Double = {
@tailrec def recurse(a: List[T], sum: T, depth: Int): Double = {
a match {
case Nil => n.toDouble(sum) / depth
case x :: xs => recurse(xs, n.plus(sum, x), depth + 1)
}
}
recurse(a.tail, a.head, 1)
}
def median[T](a: NonEmptyList[T])(implicit n: Numeric[T]): Double = {
val list = a.list
val size = list.size
val (lower, upper) = list.sorted.splitAt(size / 2)
if (size % 2 == 0) (n.toDouble(lower.last) + n.toDouble(upper.head)) / 2.0
else n toDouble upper.head
}
def truncateAt(n: Double, p: Int): Double = {
val s = math.pow(10, p)
(math floor n * s) / s
}
def toInt(l: Long): Int = l.min(Int.MaxValue).max(Int.MinValue).toInt
def toInt(l: Option[Long]): Option[Int] = l map toInt
}
示例8: MetricOperations
//设置package包名称以及导入依赖的类
package org.singingwizard.util.collections
import scala.math.pow
import scala.math.sqrt
object MetricOperations {
implicit class SetAddDiffVector[T](val underlying: collection.Set[T]) extends AnyVal {
def differenceVector[N: Numeric](o: collection.Set[T], distance: N) = {
(underlying ++ o).toSeq.map { e ?
if (underlying(e) == o(e)) {
implicitly[Numeric[N]].zero
} else {
distance
}
}
}
def differenceVector[N: Numeric](o: collection.Set[T], distance: (T) ? N) = {
(underlying ++ o).toSeq.map { e ?
if (underlying(e) == o(e)) {
implicitly[Numeric[N]].zero
} else {
distance(e)
}
}
}
}
implicit class DoubleSeqWithAdditional(val underlying: collection.Traversable[Double]) {
def pNorm(p: Double) = {
if (p == Double.PositiveInfinity || p == Double.NegativeInfinity) {
underlying.max
} else if (p == 1) {
underlying.sum
} else if (p == 2) {
sqrt(underlying.map(x ? x * x).sum)
} else {
pow(underlying.map(pow(_, p)).sum, 1 / p)
}
}
}
implicit class IntSeqWithAdditional(val underlying: collection.Traversable[Int]) {
def pNorm(p: Double): Double = {
if (p == Double.PositiveInfinity || p == Double.NegativeInfinity) {
underlying.max
} else if (p == 1) {
underlying.sum
} else if (p == 2) {
sqrt(underlying.map(x ? x * x).sum)
} else {
pow(underlying.map(pow(_, p)).sum, 1 / p)
}
}
}
implicit class BooleanWithAdditional(val underlying: Boolean) extends AnyVal {
def ?>[N: Numeric](v: N) = if (underlying) v else implicitly[Numeric[N]].one
def !?>[N: Numeric](v: N) = if (!underlying) v else implicitly[Numeric[N]].zero
}
}
示例9: DataSetGenerator
//设置package包名称以及导入依赖的类
package de.tuberlin.cit.cost.datagen.flink
import org.apache.flink.api.scala._
import org.apache.flink.core.fs.FileSystem
import scala.concurrent.forkjoin.ThreadLocalRandom
import scala.math.pow
object DataSetGenerator {
def main(args: Array[String]) {
if (args.length != 3) {
Console.err.println("Usage: DataSetGenerator <points> <dimension> <outputPath>")
System.exit(-1)
}
val m = args(0).toInt
val n = args(1).toInt
val outputPath = args(2)
val env = ExecutionEnvironment.getExecutionEnvironment
env
.generateSequence(1, m)
.map(_ => {
val x = ThreadLocalRandom.current().nextDouble()
val noise = ThreadLocalRandom.current().nextGaussian()
// generate the function value with added gaussian noise
val label = function(x) + noise
// generate a vandermatrix from x
val vector = polyvander(x, n - 1)
(vector :+ label).mkString(" ")
})
.writeAsText(outputPath, FileSystem.WriteMode.OVERWRITE)
env.execute("Data Set Generator")
}
def polyvander(x: Double, order: Int): Array[Double] = {
(0 to order).map(pow(x, _)).toArray
}
def function(x: Double): Double = {
2 * x + 10
}
}
示例10: Vectors
//设置package包名称以及导入依赖的类
package algru.orbitcalc
import scala.math.pow
object Vectors {
type Force = Vector3
type Coords = Vector3
def zeroVector = new Vector3(0, 0, 0)
}
class Vector3(val dx: Double, val dy: Double, val dz: Double) {
def x(vector: Vector3): Vector3 = {
new Vector3(
dy * vector.dz - dz * vector.dy,
dz * vector.dx - dx * vector.dz,
dx * vector.dy - dy * vector.dx
)
}
def *(vector: Vector3): Double = {
dx * vector.dx + dy * vector.dy + dz * vector.dz
}
def *(c: Double): Vector3 = {
new Vector3(dx * c, dy * c, dz * c)
}
def /(c: Double): Vector3 = {
new Vector3(dx / c, dy / c, dz / c)
}
def +(vector: Vector3): Vector3 = {
new Vector3(
dx + vector.dx,
dy + vector.dy,
dz + vector.dz
)
}
def -(vector: Vector3): Vector3 = {
new Vector3(
dx - vector.dx,
dy - vector.dy,
dz - vector.dz
)
}
val module: Double = pow(dx * dx + dy * dy + dz * dz, 0.5)
override def toString: String = s"($dx, $dy. $dz)"
}
示例11: Orbit
//设置package包名称以及导入依赖的类
package algru.orbitcalc
import algru.orbitcalc.Vectors.{Coords, Force}
import algru.orbitcalc.units.{Meter, StdGravityParameterUnit}
import scala.math.pow
class Orbit(val a: Meter,
val b: Meter,
val E: Force,
val centralBody: Coords) {
val e: Double = E.module
val c: Double = a * e
val center: Coords = centralBody - (E * (c / e))
lazy val apocenter: Coords = centralBody - (E * (a + c) / e)
lazy val pericenter: Coords = centralBody + (E * (a - c) / e)
override def toString: String = s"a=$a, b=$b, center=$center, apocenter=$apocenter, pericenter=$pericenter"
}
object OrbitCalculator {
def findOrbit(orbitingBody: SpaceObject): Orbit = {
if (orbitingBody.orbitedObject.isDefined) {
val centralBody = orbitingBody.orbitedObject.get
val positionVector = orbitingBody.position - centralBody.position
val eccentricityVector = findEccentricityVector(positionVector, orbitingBody.velocity, centralBody.body.mu)
val angularMomentumSqr = pow(findAngularMomentum(positionVector, orbitingBody.velocity).module, 2)
val semiMajorAxis = angularMomentumSqr / (centralBody.body.mu * (1 - pow(eccentricityVector.module, 2)))
val semiMinorAxis = angularMomentumSqr / (centralBody.body.mu * pow(1 - pow(eccentricityVector.module, 2), 0.5))
new Orbit(semiMajorAxis, semiMinorAxis, eccentricityVector, centralBody.position)
} else {
new Orbit(0, 0, Vectors.zeroVector, orbitingBody.position)
}
}
def findEccentricityVector(position: Coords, velocity: Force, stdGravityParameter: StdGravityParameterUnit): Coords = {
(position * (pow(velocity.module, 2) - stdGravityParameter / position.module) - (velocity * (position * velocity))) / stdGravityParameter
}
def findAngularMomentum(position: Coords, velocity: Force): Coords = position x velocity
}
示例12: Strategy
//设置package包名称以及导入依赖的类
package com.hombredequeso.robbierobot
import com.hombredequeso.robbierobot.Action._
import com.hombredequeso.robbierobot.Content._
import com.hombredequeso.util.RND.ScalaRandomizer
import com.hombredequeso.util.{RND, RandomProvider}
import scala.math.pow
object Strategy {
case class Scenario(
val north: Content,
val south: Content,
val east: Content,
val west: Content,
val current: Content
) extends Ordered[Scenario]
{
def toOrderValue(): Double = {
val max = Content.maxId
north.id +
(south.id * max) +
(east.id * pow(max, 2)) +
(west.id * pow(max, 3)) +
(current.id * pow(max, 4))
}
override def compare(that: Scenario): Int = {
val x1 = this.toOrderValue()
val y1 = that.toOrderValue()
x1.compare(y1)
}
}
type StrategyMap = Map[Scenario, Action]
// gets the fitness of a strategy, taking a RandomProvider (stateful),
// and returns the new stateful RandomProvider
def getStrategyFitness
(randomizer: RandomProvider)
(boardCount: Int, numberOfTurnsPerBoard: Int)
(strategy: StrategyMap)
: (Int, RandomProvider) = {
val (randomSeeds, newRandomizer) = RND.nextN(boardCount)(r => r.nextInt)(randomizer)
val boards = randomSeeds
.par
.map(x => Board.createRandomBoard(new ScalaRandomizer(x))(10, 10, 0.5f))
val r = new ScalaRandomizer()
val fitness = boards.map(b =>
Play.execute(randomizer)(
Play.State(b, Play.initialRobotPosition),
strategy,
numberOfTurnsPerBoard))
(fitness.sum, newRandomizer)
}
}
示例13: Edge
//设置package包名称以及导入依赖的类
package skeleton
import display.fmt
import util.{Vec, TwoD}
import scala.math.{pow, abs, sqrt}
class Edge(val a: Corner, val b: Corner) {
def asVec(): Vec = {
return b-a
}
def distance(p: TwoD): Double = {
abs((b.y - a.y)*p.x - (b.x - a.x)*p.y + b.x*a.y - b.y*a.x) / sqrt(pow(b.y - a.y, 2) + pow(b.x - a.x, 2))
}
override def toString(): String = {
"Edge(" + a + ", " + b + ")"
}
override def equals(o: Any): Boolean = o match {
case e: Edge => e.a == a && e.b == b
case _ => false
}
override def hashCode = {
(a.x + a.y + b.x + b.y).hashCode()
}
}
object Edge {
val debug = new Edge(new Corner(0,0), new Corner(1,0))
def bisector(ep: Edge, en: Edge): Vec = {
(-ep.asVec().unit + en.asVec().unit).unit
}
}
示例14: CoordinateSystem
//设置package包名称以及导入依赖的类
package net.pitpit.quadtree
import scala.math.pow
object CoordinateSystem {
final val SPACE_MIN_X = -180.0D
final val SPACE_MAX_X = 180.0D
final val SPACE_MIN_Y = -90.0D
final val SPACE_MAX_Y = 90.0D
final val MAX_DEPTH = 20
final val DEPTH_SIZES_X: Array[Double] = {
val zero = SPACE_MAX_X - SPACE_MIN_X
Range(0, MAX_DEPTH).map(depth => zero / pow(2, depth)).toArray
}
final val DEPTH_SIZES_Y: Array[Double] = {
val zero = SPACE_MAX_Y - SPACE_MIN_Y
Range(0, MAX_DEPTH).map(depth => zero / pow(2, depth)).toArray
}
}
示例15: Maths
//设置package包名称以及导入依赖的类
package lila.common
import scala.annotation._
import scala.math.{ pow, sqrt }
import scalaz.{ NonEmptyList, IList, INil, ICons }
object Maths {
def variance[T](a: NonEmptyList[T])(implicit n: Numeric[T]): Double = {
val m = mean(a)
a.map(i => pow(n.toDouble(i) - m, 2)).toList.sum / a.size
}
def deviation[T](a: NonEmptyList[T])(implicit n: Numeric[T]): Double = sqrt(variance(a))
// ridiculously performance optimized mean function
def mean[T](a: NonEmptyList[T])(implicit n: Numeric[T]): Double = {
@tailrec def recurse(a: IList[T], sum: T, depth: Int): Double = {
a match {
case ICons(x, xs) => recurse(xs, n.plus(sum, x), depth + 1)
case _ => n.toDouble(sum) / depth
}
}
recurse(a.tail, a.head, 1)
}
def median[T](a: NonEmptyList[T])(implicit n: Numeric[T]): Double = {
val list = a.toList
val size = a.size
val (lower, upper) = list.sorted.splitAt(size / 2)
if (size % 2 == 0) (n.toDouble(lower.last) + n.toDouble(upper.head)) / 2.0
else n toDouble upper.head
}
def truncateAt(n: Double, p: Int): Double = {
val s = math.pow(10, p)
(math floor n * s) / s
}
def toInt(l: Long): Int = l.min(Int.MaxValue).max(Int.MinValue).toInt
def toInt(l: Option[Long]): Option[Int] = l map toInt
}