Home »
Scala
Scala Power (Exponentiation) Function
By IncludeHelp Last updated : November 16, 2024
Scala programming language has a huge set of libraries to support different functionalities.
scala.math.pow()
The pow() function is used for the exponential mathematical operation,
This method can be accessed from scala.math library directly. The function accepts two variables First number and second the power of the number up to which date exponent is to be found. And, it returns a double integer with the result of the exponential function.
Let us see, the usage of pow() function and how to implement this into a Scala program?
Example 1: Program to find square of a number
object myClass{
def main(args: Array[String]): Unit = {
var i = 5;
var p = 2;
var ans = scala.math.pow(i,p)
println("The value of "+i+" to the power of "+p+" is "+ ans)
}
}
Output
The value of 5 to the power of 2 is 25.0
Code Explanation
The above code is to find the square of the given number. To the find square of a given number, we will pass 2 to the second value of the pow() function. which returns the numbers power 2 that is its square.
Example 2: Program to find square root of a number
object myClass{
def main(args: Array[String]): Unit = {
var i = 25;
var p = 0.5;
var ans = scala.math.pow(i,p)
println("The value of "+i+" to the power of "+p+" is "+ ans)
}
}
Output
The value of 25 to the power of 0.5 is 5.0
Code Explanation
The above code is used to find the square root of the given number. In this program, we have used the pow() function from the Scala library. the function takes two double values and return the double value as the output of the pow() function. To find the square root we have set the second value to 0.5, which gives the square root of the number. The square root is printed in the next line using the println statement.