Skip to content

Fix TensorExtensions.StdDev #110392

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Dec 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should indeed be updated to use IRootFunctions instead; not Pow which isn't guaranteed to behave the same in many important edge cases

}
#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
Loading