Improve general handling of significant figures

Fixes an issue with input of just '0', the Goodie was not triggering.
master
Ben Moon 2015-12-28 11:31:51 +00:00
parent b886023057
commit 6511199068
2 changed files with 34 additions and 28 deletions

View File

@ -10,43 +10,44 @@ triggers start => 'sigfigs', 'sigdigs', 'sf', 'sd', 'significant';
zci answer_type => "sig_figs";
zci is_cached => 1;
sub get_sig_figs {
my $num = shift;
$num =~ s/^[-+]+//;
# Leading digits NEVER contribute towards significant figures.
$num =~ s/^0+//;
$num =~ /^(?<int_part>\d*+)(\.(?<frac_part>\d*))?$/;
my $int_part = $+{'int_part'};
my $frac_part = $+{'frac_part'};
my $sigfigs = length $int_part;
if (defined $frac_part) {
# Leading zeros after decimal point aren't significant if there
# was no integer part or the integer part consisted of only zeros.
$frac_part =~ s/^0+// if $sigfigs == 0;
return $sigfigs + length $frac_part;
};
# This isn't necessarily correct - significant figures can be
# ambiguous when not using scientific notation.
$int_part =~ s/0+$//;
return length $int_part;
}
handle remainder => sub {
my $query = $_;
$query =~ s/^(figures|digits)\s*//;
$query =~ s/^(figures|digits)\s*//i;
$query =~ s/^of\s*//i;
return if $query eq '';
my $style = number_style_for($query);
return unless $style;
my $formatted_input = $style->for_display($query);
my $to_compute = $style->for_computation($query);
my $digits = $to_compute =~ s/^[-+]//r;
# Leading digits NEVER contribute towards significant figures.
$digits =~ s/^0+//;
my @arr = split('\\.', $digits);
my $v = @arr;
my $len = 0;
# there's a decimal
unless ($v eq 1) {
# the string doesn't have integers on the left
# this means we can strip the leading zeros on the right
if ($digits < 1) {
$arr[1] =~ s/^0+//;
$len = length $arr[1];
}
#there are integers on the left
else {
$len = length($arr[0]) + length($arr[1]);
}
}
# no decimal
else {
# lose the trailing zeros and count
$digits =~ s/\.?0*$//;
$len = length $digits;
}
return $len, structured_answer => {
my $sigfigs = get_sig_figs $to_compute;
return unless defined $sigfigs;
return $sigfigs, structured_answer => {
id => 'sig_figs',
name => 'Answer',
data => {
title => "$len",
title => "$sigfigs",
subtitle => "Significant figures of $formatted_input",
},
templates => {

View File

@ -36,10 +36,15 @@ ddg_goodie_test(
"sd 045.30" => build_test('4', '045.30'),
'sigfigs 01.1234000' => build_test('8', '01.1234000'),
'significant figures 000123000' => build_test('3', '000,123,000'),
'sigfigs 0' => build_test('0', '0'),
'sf 001,70' => build_test('3', '001,70'),
'sf 1_200.' => build_test('4', '1,200.'),
'sf 1. 5h' => undef,
'sig figs 501,.3' => undef,
'sf' => undef,
'significant figures a' => undef,
'significant figures of 1.230' => build_test('4', '1.230'),
'sigdigs 000.' => build_test('0', '000.'),
);
done_testing;