OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Using std::normal_distribution in function template [duplicate]

  • Thread starter Thread starter Bakkune
  • Start date Start date


I'm working on a function that generates a uniformly random point on the surface of unit d dimensional hypersphere. What I'm trying to do is to generate d random numbers with standard normal distribution to form a d dimensional vector, and then simply normalize it (Why? See here to find out: Hypersphere point picking). Here is my C++ code

#include <iostream>
#include <random> 
#include <vector>

std::random_device         _random_device;
std::mt19937               generate(_random_device());
std::normal_distribution<> standard_normal(0, 1);

template <typename type> 
std::vector<type> uniform_on_unit_sphere (const int &d) {
    std::vector<type> v(d); 
    type v_2norm_sq = 0;   
    type v_2norm_inv; 
    type rand; 

    for (int k = 0; k < d; k++) {
        rand        = standard_normal(generate); 
        v[k]        = rand;
        v_2norm_sq += rand * rand;  

    v_2norm_inv = 1.0 / std::sqrt(v_2norm_sq); 

    for (int k = 0; k < d; k++) {v[k] *= v_2norm_inv;}

    return v;

int main() {

    int d = 5; 
    std::vector<double> u = uniform_on_unit_sphere(d); 

    for (int k = 0; k < d; k++) {
        std::cout << u[k] << " "; 
    return 0; 

When I run the code, it gives an error

main.cpp: In function 'int main()':
main.cpp:45:53: error: no matching function for call to 'uniform_on_unit_sphere(int&)'
   45 |     std::vector<double> u = uniform_on_unit_sphere(d);
      |                                                     ^
main.cpp:23:19: note: candidate: 'template<class type> std::vector<_RealType> uniform_on_unit_sphere(const int&)'  
   23 | std::vector<type> uniform_on_unit_sphere (const int &d) {
      |                   ^~~~~~~~~~~~~~~~~~~~~~
main.cpp:23:19: note:   template argument deduction/substitution failed:
main.cpp:45:53: note:   couldn't deduce template parameter 'type'
   45 |     std::vector<double> u = uniform_on_unit_sphere(d);

I want to make use of template to define uniform_on_unit_sphere() that can use for all real number data types. How should I fix?
Continue reading...

Latest posts