1+ using System ;
2+ using System . Collections . Generic ;
3+ using System . Linq ;
4+ using System . Text ;
5+ using NumSharp . Core . Extensions ;
6+
7+ namespace NumSharp . Core
8+ {
9+ public partial class NDArray
10+ {
11+ public NDArray std ( int axis = - 1 , Type dtype = null )
12+ {
13+ dtype = ( dtype == null ) ? typeof ( double ) : dtype ;
14+
15+ // in case have 1D array but user still using axis 0 ... can be used like -1
16+ axis = ( axis == 0 && this . ndim == 1 ) ? - 1 : axis ;
17+
18+ Array data = this . Storage . GetData ( ) ;
19+
20+ NDArray stdArr = new NDArray ( dtype ) ;
21+
22+ if ( axis == - 1 )
23+ {
24+ double mean = this . mean ( axis ) . MakeGeneric < double > ( ) [ 0 ] ;
25+ double sum = 0 ;
26+ for ( int idx = 0 ; idx < data . Length ; idx ++ )
27+ sum += Math . Pow ( Convert . ToDouble ( data . GetValue ( idx ) ) - mean , 2 ) ;
28+
29+ double stdValue = Math . Sqrt ( sum / this . size ) ;
30+ stdArr . Storage . Allocate ( dtype , new Shape ( 1 ) , 1 ) ;
31+ var puffer = Array . CreateInstance ( dtype , 1 ) ;
32+ puffer . SetValue ( stdValue , 0 ) ;
33+ stdArr . Storage . SetData ( puffer ) ;
34+ }
35+ else
36+ {
37+ double [ ] stdValue = null ;
38+ if ( axis == 0 )
39+ {
40+ double [ ] sum = new double [ this . shape [ 1 ] ] ;
41+ stdValue = new double [ sum . Length ] ;
42+
43+ double [ ] mean = this . mean ( axis ) . Storage . GetData < double > ( ) ;
44+
45+ for ( int idx = 0 ; idx < sum . Length ; idx ++ )
46+ {
47+ for ( int jdx = 0 ; jdx < this . shape [ 0 ] ; jdx ++ )
48+ {
49+ sum [ idx ] += Math . Pow ( Convert . ToDouble ( this [ jdx , idx ] ) - mean [ idx ] , 2 ) ;
50+ }
51+ stdValue [ idx ] = Math . Sqrt ( sum [ idx ] / this . shape [ 0 ] ) ;
52+ }
53+
54+ }
55+ else if ( axis == 1 )
56+ {
57+ double [ ] sum = new double [ this . shape [ 0 ] ] ;
58+ stdValue = new double [ sum . Length ] ;
59+
60+ double [ ] mean = this . mean ( axis ) . Storage . GetData < double > ( ) ;
61+
62+ for ( int idx = 0 ; idx < sum . Length ; idx ++ )
63+ {
64+ for ( int jdx = 0 ; jdx < this . shape [ 1 ] ; jdx ++ )
65+ {
66+ sum [ idx ] += Math . Pow ( Convert . ToDouble ( this [ idx , jdx ] ) - mean [ idx ] , 2 ) ;
67+ }
68+ stdValue [ idx ] = Math . Sqrt ( sum [ idx ] / this . shape [ 1 ] ) ;
69+ }
70+ }
71+ else
72+ {
73+ throw new NotImplementedException ( ) ;
74+ }
75+ stdArr . Storage . Allocate ( dtype , new Shape ( stdValue . Length ) , 1 ) ;
76+ stdArr . Storage . SetData ( stdValue ) ;
77+ }
78+ return stdArr ;
79+ }
80+ }
81+ }
0 commit comments