C++ function the norm (magnitude) of the vector

how to calculate he norm (magnitude) of the vector A = (a1, a2, ... ,an).


#include<iostream>
using namespace std;
double norm (double [],int);
int main () {
const double n=3;
double a[3]={3,5,7};
double n;
for(int i=0;i<3;i++)
cout<<a[i]<<endl;
n=norm(a,3);
return 0;
}
double norm(double x[],int size) {
I couldnt continue .I tried writing a suitable code but I coundnt how can I solve this guestion?Could anyone help me please?

1
2
3
4
5
6
7
8
9
double norm(double x[],int size)
{
  int  total = 0;
  for (int i = 0; i < size; ++i)
  {
    total += x[i];
  }
  return sqrt(total);
}
@Repeater
Small typo: on line 6, you need to square each component: total += x[i] * x[i];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <numeric>
#include <cmath>

double norm( const double x[], std::size_t sz ) // *** const
{
    // http://en.cppreference.com/w/cpp/algorithm/inner_product
    return std::sqrt( std::inner_product( x, x+sz, x, 0.0 ) ) ;
}

// more expensive, but potentially with finer accuracy
double f_norm( const double x[], std::size_t sz ) // *** const
{
    double compensation = 0.0 ;

    // https://en.wikipedia.org/wiki/Kahan_summation_algorithm#The_algorithm
    const auto plus = [&compensation] ( double accumulator, double value )
    {
        const double vx = value - compensation ;
        const double ax = accumulator + vx ;
        compensation = ( ax - accumulator ) - vx ;
        return ax ;
    };

    return std::sqrt( std::inner_product( x, x+sz, x, 0.0, plus, std::multiplies<>{} ) ) ;
}

http://coliru.stacked-crooked.com/a/a7515bec8d61c9fc
http://rextester.com/ICONK84180
Topic archived. No new replies allowed.