Skip to content

Commit

Permalink
Fix TensorExtensions.StdDev (dotnet#110392)
Browse files Browse the repository at this point in the history
* Fix TensorExtensions.StdDev

* Add constraint to ref

* Revert "Add constraint to ref"

This reverts commit f740f50.

* Revert "Fix TensorExtensions.StdDev"

This reverts commit c212984.

* Use pow method

* Use existing variable
  • Loading branch information
lilinus authored and hez2010 committed Dec 14, 2024
1 parent d97abb1 commit fe9a96a
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3521,7 +3521,17 @@ public static T StdDev<T>(in ReadOnlyTensorSpan<T> x)
TensorPrimitives.Abs(output, output);
TensorPrimitives.Pow((ReadOnlySpan<T>)output, T.CreateChecked(2), output);
T sum = TensorPrimitives.Sum((ReadOnlySpan<T>)output);
return T.CreateChecked(sum / T.CreateChecked(x._shape._memoryLength));
T variance = sum / T.CreateChecked(x._shape._memoryLength);

if (typeof(T) == typeof(float))
{
return T.CreateChecked(MathF.Sqrt(float.CreateChecked(variance)));
}
if (typeof(T) == typeof(double))
{
return T.CreateChecked(Math.Sqrt(double.CreateChecked(variance)));
}
return T.Pow(variance, T.CreateChecked(0.5));
}
#endregion

Expand Down
2 changes: 1 addition & 1 deletion src/libraries/System.Numerics.Tensors/tests/TensorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1113,7 +1113,7 @@ public static float StdDev(float[] values)
{
sum += MathF.Pow(values[i] - mean, 2);
}
return sum / values.Length;
return MathF.Sqrt(sum / values.Length);
}

[Fact]
Expand Down

0 comments on commit fe9a96a

Please sign in to comment.