-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhelper.cs
More file actions
119 lines (86 loc) · 2.17 KB
/
helper.cs
File metadata and controls
119 lines (86 loc) · 2.17 KB
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
//helper functions, maybe make a class for these?
using System;
public class helperFunctions {
//may need helpers to calculate math stuff
public static double[] Zero(int n){
return new double[n];//zero vector of lenth n
}
public static double[] Copy(double[] a ){
double[] b = new double[a.Length];
Array.Copy(a, b, a.Length);
return b;
}
//adding
public static double[] Add(double[] a, double[] b)
{
int n = a.Length;
double[] c = new double[n];
for (int i = 0; i < n; i++)
c[i] = a[i] + b[i];
return c;
}
//subtracting
public static double[] Sub(double[] a, double[] b)
{
int n = a.Length;
double[] c = new double[n];
for (int i = 0; i < n; i++)
c[i] = a[i] - b[i];
return c;
}
public static double[] Scale(double[] a, double s)
{
int n = a.Length;
double[] b = new double[n];
for (int i = 0; i < n; i++)
b[i] = s * a[i];
return b;
}
//finds eucliedean norm
public static double Norm(double[] a)
{
double sum = 0.0;
for (int i = 0; i < a.Length; i++)
sum += a[i] * a[i];
return Math.Sqrt(sum);
}
//dot product
public static double Dot(double[] a, double[] b)
{
double sum = 0.0;
for (int i = 0; i < a.Length; i++)
sum += a[i] * b[i];
return sum;
}
//clamping each element to min,max
public static double[] Clamp(double[] a, double min, double max)
{
int n = a.Length;
double[] b = new double[n];
for (int i = 0; i < n; i++)
{
if (a[i] < min) b[i] = min;
else if (a[i] > max) b[i] = max;
else b[i] = a[i];
}
return b;
}
//gradient helper
public static double[] FiniteDifferenceGradient(
Func<double[], double> f,
double[] x,
double eps = 1e-6)
{
int n = x.Length;
double[] grad = new double[n];
double[] xPerturbed = helperFunctions.Copy(x);
double f0 = f(x);
for (int i = 0; i < n; i++)
{
xPerturbed[i] += eps;
grad[i] = (f(xPerturbed) - f0) / eps;
xPerturbed[i] = x[i];
}
return grad;
}
}