本文整理汇总了Scala中scala.math.sqrt类的典型用法代码示例。如果您正苦于以下问题:Scala sqrt类的具体用法?Scala sqrt怎么用?Scala sqrt使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了sqrt类的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。
示例1: sumElements
//设置package包名称以及导入依赖的类
import scala.annotation.tailrec
import scala.collection.GenSeq
import scala.math.sqrt
package object PageRank {
type LinkMat = GenSeq[(Int,Int)]
def sumElements(R: GenSeq[Float], A: LinkMat, j: Int): Float = {
// sums all PageRanks / number of links for a column j
val totalLinks = A.filter(_._2==j)
if (totalLinks.isEmpty) sys.error("No link in the page " + j + " at sumElements")
else R(j)/totalLinks.size
}
// find all pages pointing to i A(i,j) exists
def findConnected(i: Int, A: LinkMat):GenSeq[Int] = A.filter(_._1==i).map(_._2).toSeq
def converged(r1: GenSeq[Float], r2: GenSeq[Float], eps: Float): Boolean = {
val totSquare: Float = r1.zip(r2).map(p=>(p._1-p._2)*(p._1-p._2)).sum
sqrt(totSquare/r1.size)<=eps
}
@tailrec def compRank(R: GenSeq[Float], A: LinkMat, damp: Float, eps: Float, niter: Int = 0,niterMax: Int = 10000): GenSeq[Float] = {
val rankIndex: GenSeq[Int] = 0 until R.size
val rightRank: GenSeq[Float] = rankIndex map{i:Int =>
val connected = findConnected(i,A)
connected.map{j:Int => sumElements(R, A, j)}.sum
}
val newRank = rightRank map {damp*_ + (1-damp)/R.size}
if(converged(newRank,R,eps)) newRank
else if(niter>=niterMax) {
println("Max iteration reached")
newRank
} else compRank(newRank,A,damp,eps,niter+1,niterMax)
}
}
开发者ID:mbesancon,项目名称:PageRank,代码行数:38,代码来源:package.scala
示例2: partitionIntoPatches
//设置package包名称以及导入依赖的类
package com.hugemane.sudoku.solver.service.partition
import com.hugemane.sudoku.solver.BoardPoint.Point
import com.hugemane.sudoku.solver.model.{ Block, SudokuBoard }
import scala.math.sqrt
trait BoardPatchPartitioner {
def partitionIntoPatches(board: SudokuBoard): List[Map[Point, Block]] = {
val rowSeparation = sqrt(board.rows)
val columnSeparation = sqrt(board.columns)
//todo: solve (get past for now to solve maximum amount of problems)
val patch1 = board.blocks.filter(x => List((0, 0), (0, 1), (1, 0), (1, 1)).contains(x._1))
val patch2 = board.blocks.filter(x => List((0, 2), (0, 3), (1, 2), (1, 3)).contains(x._1))
val patch3 = board.blocks.filter(x => List((2, 0), (2, 1), (3, 0), (3, 1)).contains(x._1))
val patch4 = board.blocks.filter(x => List((2, 2), (2, 3), (3, 2), (3, 3)).contains(x._1))
List(patch1, patch2, patch3, patch4)
}
}
开发者ID:hugemane,项目名称:sudoku-solver,代码行数:23,代码来源:BoardPatchPartitioner.scala
示例3: ExerciseTenSpec
//设置package包名称以及导入依赖的类
package chapter.fourteen
import ExerciseTen.compose
import scala.math.sqrt
import org.scalatest._
import org.scalatest.junit.JUnitRunner
import org.junit.runner.RunWith
@RunWith(classOf[JUnitRunner])
class ExerciseTenSpec extends FlatSpec with Matchers {
"compose" should "compose two functions, yielding another function of the same type" in {
def f(x: Double) = if (x >= 0) Some(sqrt(x)) else None
def g(x: Double) = if (x != 1) Some(1 / (x - 1)) else None
val h = compose(f, g)
h(2) should be ( Some(1.0) )
h(1) should be ( None )
h(0) should be ( None )
}
}
开发者ID:deekim,项目名称:impatient-scala,代码行数:24,代码来源:ExerciseTenSpec.scala
示例4: 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)
}
}
开发者ID:dotdeb,项目名称:Science-Finder,代码行数:33,代码来源:VectorUtils.scala
示例5: 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
}
开发者ID:DrNixx,项目名称:line,代码行数:43,代码来源:Maths.scala
示例6: 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
}
}
开发者ID:arthurp,项目名称:genetic-prographs,代码行数:62,代码来源:MetricOperations.scala
示例7: swap
//设置package包名称以及导入依赖的类
package com.cds.learnscala.chapter.chp14
import scala.None
def swap[S, T](tup: (S, T)): (T, S) = {
tup match {
case (a, b) => (b, a)
}
}
def swap1(array: Array[Any]) = {
array match {
case Array(first, second, [email protected]_*) => Array(second, first) ++ rest
case _ => array
}
}
def sum(lst: List[Option[Int]]) = {
lst.map(_.getOrElse(0)).sum
}
def sum1(lst: List[Option[Int]]) = {
var result = 0
lst.foreach {
case Some(a) => result += a
case None => result
}
result
}
def compose(f: Double => Option[Double], g: Double => Option[Double]) = {
(x: Double) =>
if (f(x) == None || g(x) == None) None
else g(x)
}
import scala.math.sqrt
def f(x: Double) = if (x >= 0) Some(sqrt(x)) else None
def g(x: Double) = if (x != 1) Some(1 / (x - 1)) else None
def main(args: Array[String]) {
println(swap[String, Int](("1", 2)))
println(swap1(Array("1", "2", "3", "4")).mkString(","))
val x = List(Some(1), None, Some(2), None, Some(3))
println(sum(x))
println(sum1(x))
val h = compose(f, g)
println(h(2))
}
}
开发者ID:anancds,项目名称:scala-project,代码行数:60,代码来源:CaseClassTest.scala
示例8: 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
}
}
开发者ID:nick-parker,项目名称:skel2d,代码行数:33,代码来源:Edge.scala
示例9: 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
}
开发者ID:Thiediev,项目名称:lilylichessmod,代码行数:43,代码来源:Maths.scala
示例10: FuturesPricing
//设置package包名称以及导入依赖的类
package pt1.week4
import breeze.linalg.{DenseMatrix, DenseVector}
import scala.math.{exp, sqrt}
object FuturesPricing {
def calculateForShares(sharePriceLattice: DenseMatrix[Double], termInYears: Double, volatility: Double,
numberOfPeriods: Int, interestRate: Double, dividendYield: Double): Double = {
val result = calculatePricingMatrix(sharePriceLattice, termInYears, volatility, numberOfPeriods, interestRate, dividendYield)
result.apply(0, 0)
}
def calculate(priceLattice: DenseMatrix[Double], numberOfPeriods: Int, q: Double, p: Double): Double = {
val result = calculatePricingMatrix(priceLattice, numberOfPeriods, q, p)
result.apply(0, 0)
}
private[week4] def calculatePricingMatrix(sharePriceLattice: DenseMatrix[Double], termInYears: Double, volatility: Double, numberOfPeriods: Int, interestRate: Double, dividendYield: Double): DenseMatrix[Double] = {
val u: Double = exp(volatility * sqrt(termInYears / numberOfPeriods))
val d: Double = 1 / u
val q: Double = (exp((interestRate - dividendYield) * termInYears / numberOfPeriods) - d) / (u - d)
val p: Double = 1 - q
calculatePricingMatrix(sharePriceLattice, numberOfPeriods, q, p)
}
private def calculatePricingMatrix(priceLattice: DenseMatrix[Double], numberOfPeriods: Int, q: Double, p: Double): DenseMatrix[Double] = {
val n = numberOfPeriods + 1
val result = DenseMatrix.zeros[Double](n, n)
val lastColumnIndex = numberOfPeriods
result(::, lastColumnIndex) := priceLattice(::, lastColumnIndex).slice(0, n)
val columnsFromPriorToLastOneDownToFirst = (lastColumnIndex - 1) to 0 by -1
for (i <- columnsFromPriorToLastOneDownToFirst) {
val previousColumn = result(::, i + 1)
val previousColumnShiftedOneDown = DenseVector.vertcat(previousColumn(1 until previousColumn.length), DenseVector.zeros[Double](1))
val currentColumn = (previousColumnShiftedOneDown * q) + (previousColumn * p)
result(::, i) += currentColumn
}
result
}
}
开发者ID:ligasgr,项目名称:fe-and-rm,代码行数:46,代码来源:FuturesPricing.scala
示例11: Metric
//设置package包名称以及导入依赖的类
package com.codiply.barrio.geometry
import scala.math.sqrt
import com.codiply.barrio.geometry.Point.Coordinates
final case class Metric(
easyDistance: (Coordinates, Coordinates) => EasyDistance,
easyDistanceToPlane: PartitioningPlane => Option[Coordinates => EasyDistance],
toEasyDistance: RealDistance => Option[EasyDistance],
toRealDistance: EasyDistance => Option[RealDistance])
final object Metric {
import com.codiply.barrio.geometry.Point.Coordinates._
val euclidean = Metric(
easyDistance = (a: Coordinates, b: Coordinates) => EasyDistance(
a.zip(b).map(t => {
val diff = t._1 - t._2
diff * diff
}).sum),
easyDistanceToPlane = (plane: PartitioningPlane) => {
// This is a vector normal to the boundary
val eta = subtract(plane.centroid1, plane.centroid2)
val etaLengthSquared = innerProduct(eta, eta)
if (etaLengthSquared == 0) {
None
} else {
val midPoint = scale(0.5, add(plane.centroid1, plane.centroid2))
Some((q: Coordinates) => {
val qToMidpoint = subtract(midPoint, q)
val product = innerProduct(qToMidpoint, eta)
EasyDistance((product * product) / etaLengthSquared)
})
}
},
toEasyDistance = (realDistance: RealDistance) =>
Some(EasyDistance(realDistance.value * realDistance.value)),
toRealDistance = (easyDistance: EasyDistance) => {
if (easyDistance.value < 0.0) {
None
} else {
Some(RealDistance(sqrt(easyDistance.value)))
}
})
}
开发者ID:codiply,项目名称:barrio,代码行数:47,代码来源:Metric.scala
示例12: Polynomial
//设置package包名称以及导入依赖的类
package calculator
object Polynomial {
def computeDelta(a: Signal[Double], b: Signal[Double], c: Signal[Double]): Signal[Double] = {
Signal {
(b() * b()) - (4 * a() * c())
}
}
def computeSolutions(a: Signal[Double], b: Signal[Double], c: Signal[Double], delta: Signal[Double])
: Signal[Set[Double]] = {
Signal {
import scala.math.sqrt
if (a() == 0 || delta() < 0)
Set()
else if (((-b() + sqrt(delta())) / (2 * a())) == ((-b() - sqrt(delta())) / (2 * a()))) {
Set(((-b() + sqrt(delta())) / (2 * a())))
} else {
Set(((-b() + sqrt(delta())) / (2 * a())), ((-b() - sqrt(delta())) / (2 * a())))
}
}
}
}
开发者ID:anand-singh,项目名称:scala-design,代码行数:26,代码来源:Polynomial.scala
注:本文中的scala.math.sqrt类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论