Skip to content

Instantly share code, notes, and snippets.

@kevmoo
Last active May 22, 2025 09:41
Show Gist options
  • Save kevmoo/08727c491098689460ce831f9b397877 to your computer and use it in GitHub Desktop.
Save kevmoo/08727c491098689460ce831f9b397877 to your computer and use it in GitHub Desktop.
Negative zero and simplifying Dart code
void main() {
// Define different scenarios for t5 using Dart records
// (String name, double t5_value, String expected_behavior)
final List<(String name, double t5Value, String expectedBehavior)> scenarios =
[
('t5 is a regular number', 1.0, 'Simplification is okay'),
(
't5 is positive Infinity',
double.infinity,
'Simplification breaks due to NaN',
),
(
't5 is negative Infinity',
double.negativeInfinity,
'Simplification breaks due to NaN',
),
(
't5 is NaN (Not a Number)',
double.nan,
'Simplification breaks due to NaN',
),
];
// Common values for other variables
double t3 = 2.0;
double left = 5.0;
double t4 = 3.0;
double top = 4.0;
double t6 = 10.0;
for (var scenario in scenarios) {
// Destructure the record for easier access
final (name, t5, expectedBehavior) = scenario;
print('--- Scenario: $name ---');
print('Expected behavior: $expectedBehavior');
// Original expression: t3 * left + t4 * top + t5 * 0 + t6
double originalExpressionResult = t3 * left + t4 * top + t5 * 0.0 + t6;
// Simplified expression: t3 * left + t4 * top + t6
double simplifiedExpressionResult = t3 * left + t4 * top + t6;
print('Original expression (t5 * 0.0): $originalExpressionResult');
print('Simplified expression (removed 0.0): $simplifiedExpressionResult');
// Special handling for NaN comparison, as NaN != NaN
bool areEqual;
if (originalExpressionResult.isNaN && simplifiedExpressionResult.isNaN) {
areEqual =
true; // Both are NaN, so they are "equal" in terms of being invalid
} else {
areEqual = originalExpressionResult == simplifiedExpressionResult;
}
print('Are they equal? $areEqual');
print('Is original result NaN? ${originalExpressionResult.isNaN}');
print('Is simplified result NaN? ${simplifiedExpressionResult.isNaN}\n');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment