Home »
C++ STL
valarray log() Function in C++ with Examples
C++ valarray log() Function: Here, we will learn about the log() function, its usages, syntax and examples.
Submitted by Shivang Yadav, on May 12, 2022
The valarray class in C++ is a special container that is used for holding elements like an array and performing operations on them.
Mathematical Log Value:
Log or logarithm is the exponent or power value to which the given base value is raised in order to yield the given number.
For expression,
ba = x
Logbx = a
log b (a) = x => a = ba
std::log(std::valarray) Function
The log() function of the valarray class is used to calculate the value of the log of elements of the valarray. It returns a valarray with each element calculated using log() function.
Syntax:
template< class T >
valarray<T> log( const valarray<T>& va );
// or
log(valarrayName)
Parameter(s): It accepts a single parameter which is the original valarray.
Return Value: It returns a valarray with the logarithmic value of each element of the original valarray.
C++ valarray log() Function Example 1:
#include <iostream>
#include <valarray>
using namespace std;
int main()
{
// Declaring valarray
valarray<double> myvalarr = { 3, 6, 2, 5, 1 };
// Printing the elements of valarray
cout << "The elements of orignal valarray are : ";
for (double& ele : myvalarr)
cout << ele << " ";
// Creating a new valarray
valarray<double> logValarray;
logValarray = log(myvalarr);
cout << "\nThe elements of logarithmic valarray are : ";
for (double& ele : logValarray)
cout << ele << " ";
return 0;
}
Output:
The elements of orignal valarray are : 3 6 2 5 1
The elements of logarithmic valarray are : 1.09861 1.79176 0.693147 1.60944 0
C++ valarray log() Function Example 2:
#include <iostream>
#include <valarray>
using namespace std;
int main()
{
// Declaring valarray
valarray<double> myvalarr = { 3.1, -6, 0.2, 5, 1.7 };
// Printing the elements of valarray
cout << "The elements of orignal valarray are : ";
for (double& ele : myvalarr)
cout << ele << " ";
// Creating a new valarray
valarray<double> logValarray;
logValarray = log(myvalarr);
cout << "\nThe elements of logarithmic valarray are : ";
for (double& ele : logValarray)
cout << ele << " ";
return 0;
}
Output:
The elements of orignal valarray are : 3.1 -6 0.2 5 1.7
The elements of logarithmic valarray are : 1.1314 -nan -1.60944 1.60944 0.530628