Skip to content

Instantly share code, notes, and snippets.

@leksak
Created December 21, 2015 09:42
Show Gist options
  • Save leksak/d548f9e794a1839a1deb to your computer and use it in GitHub Desktop.
Save leksak/d548f9e794a1839a1deb to your computer and use it in GitHub Desktop.
Inspect differing digits in decimal expansion
function [n, difference] = decimal_expansion_difference(target, actual, pertinent_digits)
%DECIMAL_EXPANSION_DIFFERENCE Inspect differing digits in decimal expansion
%
% INPUT:
% target the target value.
% actual the computed value, its distance must be < 1 away from target.
% If violated you will incur an assertion error.
% pertinent_digits an upper bound for beyond which we stop caring about the amount
% of differing digits in the decimal expansion.
%
% OUTPUT:
% n at most pertinent_digits, otherwise the amount of differing digits.
% difference the n digits that differ between the two numbers, target and actual.
%
% MINIMUM WORKING EXAMPLE (MWE)
%
% % Choose a target number
% target = 4;
%
% % Another number which satisfies the condition that its distance
% % to the target is less than 1.
% actual = 3.997254177740000;
%
% % Get how many digits differ between the pair, n, and which digits those are.
% [n, difference] = digit_distance(target, actual, 10)
%
% n =
%
% 7
%
% difference =
%
% 2745822
% Get, symbolically, the difference, between the target and the actual
% value. This contains a lot of digits.
assert(abs(target - actual) < 1);
digits(pertinent_digits);
difference = char(abs(sym(target, 'd') - sym(actual, 'd')));
% Remove the leading "0."
difference = difference(3:end);
% Remove leading zeroes
difference = regexprep(difference, '^[0]+', '');
% Remove trailing zeroes
difference = regexprep(difference, '[0]+$', '');
n = numel(difference);
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment