{"id":38,"date":"2006-05-24T08:08:46","date_gmt":"2006-05-24T13:08:46","guid":{"rendered":"https:\/\/blogs.mathworks.com\/loren\/?p=38"},"modified":"2019-02-01T09:46:01","modified_gmt":"2019-02-01T14:46:01","slug":"programming-for-multiple-datatypes","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/loren\/2006\/05\/24\/programming-for-multiple-datatypes\/","title":{"rendered":"Programming for Multiple Datatypes"},"content":{"rendered":"<div xmlns:mwsh=\"https:\/\/www.mathworks.com\/namespace\/mcode\/v1\/syntaxhighlight.dtd\" class=\"content\">\r\n   <introduction>\r\n      <p>How do you write M-files in MATLAB that you would like to have work correctly whether the inputs are double precision or single?\r\n         By correctly, I mean that the program gives an answer appropriate to the precision of the input.\r\n      <\/p>\r\n   <\/introduction>\r\n   <h3>Contents<\/h3>\r\n   <div>\r\n      <ul>\r\n         <li><a href=\"#1\">Special Constants and Functions in MATLAB to Help with Precision<\/a><\/li>\r\n         <li><a href=\"#2\">Problem Description<\/a><\/li>\r\n         <li><a href=\"#3\">Golden Mean<\/a><\/li>\r\n         <li><a href=\"#5\">How Many Fibonacci Terms Should We Compute?<\/a><\/li>\r\n         <li><a href=\"#7\">Calculate Number of Terms<\/a><\/li>\r\n         <li><a href=\"#8\">Double Algorithm<\/a><\/li>\r\n         <li><a href=\"#9\">Floating Point Algorithm<\/a><\/li>\r\n         <li><a href=\"#10\">Number of Terms for Single and Double<\/a><\/li>\r\n         <li><a href=\"#12\">Tools in MATLAB for Writing \"Generic\" Floating Point Programs<\/a><\/li>\r\n      <\/ul>\r\n   <\/div>\r\n   <h3>Special Constants and Functions in MATLAB to Help with Precision<a name=\"1\"><\/a><\/h3>\r\n   <p>There are some fairly new functions in MATLAB to help with precision, and some updates to existing functions.  Let me first\r\n      list some \"constants\" that might be interesting for working with different precision data:\r\n   <\/p>\r\n   <div>\r\n      <ul>\r\n         <li><tt>eps<\/tt><\/li>\r\n         <li><tt>zeros<\/tt>, <tt>ones<\/tt>, <tt>Inf<\/tt><\/li>\r\n      <\/ul>\r\n   <\/div>\r\n   <p>There are several places in the documentation that are also particularly relevant:<\/p>\r\n   <div>\r\n      <ul>\r\n         <li><a href=\"https:\/\/www.mathworks.com\/help\/matlab\/matlab_prog\/floating-point-numbers.html\">Floating Point Numbers<\/a><\/li>\r\n         <li><a title=\"https:\/\/www.mathworks.com\/help\/matlab\/matlab_prog\/function-summary.html#bqjg7rx (link no longer works)\">Floating Point Functions<\/a><\/li>\r\n         <li><a title=\"https:\/\/www.mathworks.com\/help\/matlab\/matlab_prog\/special-values.html (link no longer works)\">Special Values<\/a><\/li>\r\n      <\/ul>\r\n   <\/div>\r\n   <p>And <a href=\"https:\/\/www.mathworks.com\/company\/aboutus\/founders\/clevemoler.html\">Cleve<\/a> wrote <a href=\"https:\/\/www.mathworks.com\/content\/dam\/mathworks\/mathworks-dot-com\/company\/newsletters\/news_notes\/pdf\/Fall96Cleve.pdf\">this article<\/a> for News and Notes in 1996 on floating point.\r\n   <\/p>\r\n   <h3>Problem Description<a name=\"2\"><\/a><\/h3>\r\n   <p>Let's write a program that calculates a result either in single or double precision, depending on the input.  <a href=\"https:\/\/blogs.mathworks.com\/loren\/?p=37\">Fibonacci numbers<\/a> are a sequence of numbers with some interesting characteristics.  As you calculate more numbers in the sequence, the ratio\r\n      between successive Fibonacci numbers approaches the golden mean or <a href=\"http:\/\/en.wikipedia.org\/wiki\/Golden_ratio\">golden ratio<\/a>.  In other words,\r\n   <\/p>\r\n   <p><img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/images\/loren\/38\/numFib_eq45564.png\"> <\/p>\r\n   <p>My current web search found 42,000,000 pages for golden mean, 9,490,000 for golden ratio - wow!<\/p>\r\n   <h3>Golden Mean<a name=\"3\"><\/a><\/h3>\r\n   <p>The golden mean can expressed as<\/p>\r\n   <p><img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/images\/loren\/38\/numFib_eq7894.png\"> <\/p>\r\n   <p>What is its value, in double precision?<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">format <span style=\"color: #A020F0\">long<\/span>\r\nGoldenMeanDouble = (1+sqrt(5))\/2<\/pre><pre style=\"font-style:oblique\">\r\nGoldenMeanDouble =\r\n\r\n   1.61803398874989\r\n\r\n<\/pre><p>What about single precision?<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">GoldenMeanSingle = (1+sqrt(single(5)))\/2<\/pre><pre style=\"font-style:oblique\">\r\nGoldenMeanSingle =\r\n\r\n   1.6180340\r\n\r\n<\/pre><h3>How Many Fibonacci Terms Should We Compute?<a name=\"5\"><\/a><\/h3>\r\n   <p>How many terms in the Fibonacci sequence should we compute so that the ratio between successive terms doesn't change our estimate\r\n      of the golden mean to within the appropriate precision?  First, stop and take a guess for both double and single precision.\r\n       Let's start with double, using the filter code from the previous blog to calculate the Fibonacci numbers.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">format\r\nnf = 100;\r\nx = [1 zeros(1,nf-1)];\r\na = [1 -1 -1];\r\nb = 1;\r\nFibDouble = filter(b, a, x);<\/pre><p>Calculate a few of the ratios and compare to the golden mean.<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">RatioDouble = FibDouble(2:11).\/FibDouble(1:10)\r\nResidualDouble = FibDouble(2:11).\/FibDouble(1:10) - GoldenMeanDouble<\/pre><pre style=\"font-style:oblique\">\r\nRatioDouble =\r\n\r\n  Columns 1 through 6 \r\n\r\n    1.0000    2.0000    1.5000    1.6667    1.6000    1.6250\r\n\r\n  Columns 7 through 10 \r\n\r\n    1.6154    1.6190    1.6176    1.6182\r\n\r\n\r\nResidualDouble =\r\n\r\n  Columns 1 through 6 \r\n\r\n   -0.6180    0.3820   -0.1180    0.0486   -0.0180    0.0070\r\n\r\n  Columns 7 through 10 \r\n\r\n   -0.0026    0.0010   -0.0004    0.0001\r\n\r\n<\/pre><h3>Calculate Number of Terms<a name=\"7\"><\/a><\/h3>\r\n   <p>Here are the number of terms needed for double precision. Most people expect the number of required terms to be considerably\r\n      higher.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">numdouble = goldFibDouble\r\nResidDouble = FibDouble(numdouble)\/FibDouble(numdouble-1) - GoldenMeanDouble<\/pre><pre style=\"font-style:oblique\">\r\nnumdouble =\r\n\r\n    41\r\n\r\n\r\nResidDouble =\r\n\r\n     0\r\n\r\n<\/pre><h3>Double Algorithm<a name=\"8\"><\/a><\/h3>\r\n   <p>Let's look at the algorithm.  In this M-file, I do not worry about efficiency for calculating the Fibonacci sequence, but<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">type <span style=\"color: #A020F0\">goldFibDouble<\/span><\/pre><pre style=\"font-style:oblique\">\r\nfunction nterms = goldFibDouble\r\n% goldFib Number of Fibonacci terms to reach golden mean ratio.\r\n\r\nfcurrent = 1;\r\nfnext = 1;\r\ngoldenMean = (1+sqrt(5))\/2;\r\ntol = eps(goldenMean);  % Calculate increment for next closest number.\r\nnterms = 2;\r\nwhile abs(fnext\/fcurrent - goldenMean) &gt;= tol\r\n    nterms = nterms + 1;\r\n    temp  = fnext;\r\n    fnext = fnext + fcurrent;\r\n    fcurrent = temp;\r\nend\r\n\r\n<\/pre><h3>Floating Point Algorithm<a name=\"9\"><\/a><\/h3>\r\n   <p>What do I need to change in <tt>goldFibDouble<\/tt> to allow it to also calculate the number of terms for single precision?  There are really only a few things I need to change.\r\n       First, I probably want to calculate the Fibonacci numbers themselves in single, and the golden mean and tolerance.  Finally,\r\n      I need to change the function so I can specify what precision I want the output to be.  Let's now look at <tt>goldFib<\/tt> where I made the necessary changes.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">dbtype <span style=\"color: #A020F0\">goldFib<\/span><\/pre><pre style=\"font-style:oblique\">\r\n1     function nterms = goldFib(dtype)\r\n2     % goldFib Number of Fibonacci terms to reach golden mean ratio.\r\n3     \r\n4     fcurrent = ones(dtype);\r\n5     fnext = fcurrent;\r\n6     goldenMean = (1+sqrt(cast(5,dtype)))\/2;\r\n7     tol = eps(goldenMean);\r\n8     nterms = 2;\r\n9     while abs(fnext\/fcurrent - goldenMean) &gt;= tol\r\n10        nterms = nterms + 1;\r\n11        temp  = fnext;\r\n12        fnext = fnext + fcurrent;\r\n13        fcurrent = temp;\r\n14    end\r\n\r\n<\/pre><h3>Number of Terms for Single and Double<a name=\"10\"><\/a><\/h3>\r\n   <p>Now let's see how many terms we need for both single and double.<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">numSingle = goldFib(<span style=\"color: #A020F0\">'single'<\/span>)\r\nnumDouble = goldFib(<span style=\"color: #A020F0\">'double'<\/span>)<\/pre><pre style=\"font-style:oblique\">\r\nnumSingle =\r\n\r\n    19\r\n\r\n\r\nnumDouble =\r\n\r\n    41\r\n\r\n<\/pre><p>You'll notice that on line 7 of <tt>goldFib<\/tt>, we calculate the relative accuracy for the golden mean in the correct precision.  You can see the values here.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">TolSingle = eps(GoldenMeanSingle)\r\nTolDouble = eps(GoldenMeanDouble)<\/pre><pre style=\"font-style:oblique\">\r\nTolSingle =\r\n\r\n  1.1921e-007\r\n\r\n\r\nTolDouble =\r\n\r\n  2.2204e-016\r\n\r\n<\/pre><h3>Tools in MATLAB for Writing \"Generic\" Floating Point Programs<a name=\"12\"><\/a><\/h3>\r\n   <p>MATLAB has tools so you can create programs that work correctly on both single and double precision.  You can see with this\r\n      example that we only needed to modify a small number of lines and terms in the M-file in order to convert the file from handling\r\n      double precision only to being able to handle both single and double precision calculations appropriately.  Do you need to\r\n      do something similar?  Is it because you have large datasets and use single precision to help manage the memory? <a href=\"https:\/\/blogs.mathworks.com\/loren\/2006\/05\/24\/programming-for-multiple-datatypes\/#respond\">Let me know<\/a>.\r\n   <\/p>\r\n   <p style=\"text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray\"><br>\r\n      Published with MATLAB&reg; 7.2<br><\/p>\r\n<\/div>\r\n<!--\r\n##### SOURCE BEGIN #####\r\n%% Writing Programs for Multiple Datatypes\r\n% How do you write M-files in MATLAB that you would like to have work\r\n% correctly whether the inputs are double precision or single?  By\r\n% correctly, I mean that the program gives an answer appropriate to the\r\n% precision of the input.  \r\n%% Special Constants and Functions in MATLAB to Help with Precision\r\n% There are some fairly new functions in MATLAB to help with precision, and\r\n% some updates to existing functions.  Let me first list some \"constants\"\r\n% that might be interesting for working with different precision data:\r\n%\r\n% * |eps|\r\n% * |zeros|, |ones|, |Inf|\r\n%\r\n% There are several places in the documentation that are also particularly\r\n% relevant:\r\n%\r\n% * <https:\/\/www.mathworks.com\/access\/helpdesk\/help\/techdoc\/matlab_prog\/f2-98645.html Floating Point Numbers>\r\n% * <https:\/\/www.mathworks.com\/access\/helpdesk\/help\/techdoc\/matlab_prog\/f2-76242.html#bqjg7rx Floating Point Functions>\r\n% * <https:\/\/www.mathworks.com\/access\/helpdesk\/help\/techdoc\/matlab_prog\/f0-40959.html Special Values>\r\n%\r\n% And <https:\/\/www.mathworks.com\/company\/aboutus\/founders\/clevemoler.html Cleve> wrote  \r\n% <https:\/\/www.mathworks.com\/content\/dam\/mathworks\/mathworks-dot-com\/company\/newsletters\/news_notes\/pdf\/Fall96Cleve.pdf this article>\r\n% for News and Notes in 1996 on floating point.\r\n%\r\n%% Problem Description\r\n% Let's write a program that calculates a result either in single or double\r\n% precision, depending on the input.  <http:?p=37 Fibonacci numbers> are a\r\n% sequence of numbers with some interesting characteristics.  As you\r\n% calculate more numbers in the sequence, the ratio between successive\r\n% Fibonacci numbers approaches the golden mean or\r\n% <http:\/\/en.wikipedia.org\/wiki\/Golden_ratio golden ratio>.  In other\r\n% words,\r\n%\r\n% $$ lim_{n->\\infty} F_n \/ F_{n-1} = Golden Mean $$\r\n%\r\n%\r\n%\r\n% My current web search found 42,000,000 pages for golden mean,\r\n% 9,490,000 for golden ratio - wow!\r\n%% Golden Mean\r\n% The golden mean can expressed as\r\n%\r\n% $$ ( 1 + \\surd(5) ) \/ 2 $$\r\n%\r\n% What is its value, in double precision?\r\nformat long\r\nGoldenMeanDouble = (1+sqrt(5))\/2\r\n%%\r\n% What about single precision?\r\nGoldenMeanSingle = (1+sqrt(single(5)))\/2\r\n%% How Many Fibonacci Terms Should We Compute?\r\n% How many terms in the Fibonacci sequence should we compute so that the\r\n% ratio between successive terms doesn't change our estimate of the golden\r\n% mean to within the appropriate precision?  First, stop and take a guess\r\n% for both double and single precision.  Let's start with double, using the\r\n% filter code from the previous blog to calculate the Fibonacci numbers.\r\nformat\r\nnf = 100;\r\nx = [1 zeros(1,nf-1)];\r\na = [1 -1 -1];\r\nb = 1;\r\nFibDouble = filter(b, a, x);\r\n%%\r\n% Calculate a few of the ratios and compare to the golden mean.\r\nRatioDouble = FibDouble(2:11).\/FibDouble(1:10)\r\nResidualDouble = FibDouble(2:11).\/FibDouble(1:10) - GoldenMeanDouble\r\n\r\n%% Calculate Number of Terms\r\n% Here are the number of terms needed for double precision.\r\n% Most people expect the number of required terms to be considerably\r\n% higher.\r\nnumdouble = goldFibDouble\r\nResidDouble = FibDouble(numdouble)\/FibDouble(numdouble-1) - GoldenMeanDouble\r\n%% Double Algorithm\r\n% Let's look at the algorithm.  In this M-file, I do not worry about\r\n% efficiency for calculating the Fibonacci sequence, but \r\ntype goldFibDouble\r\n%% Floating Point Algorithm\r\n% What do I need to change in |goldFibDouble| to allow it to also calculate\r\n% the number of terms for single precision?  There are really only a few\r\n% things I need to change.  First, I probably want to calculate the\r\n% Fibonacci numbers themselves in single, and the golden mean and\r\n% tolerance.  Finally, I need to change the function so I can specify what\r\n% precision I want the output to be.  Let's now look at |goldFib| where I\r\n% made the necessary changes.\r\ndbtype goldFib\r\n%% Number of Terms for Single and Double\r\n% Now let's see how many terms we need for both single and double.\r\nnumSingle = goldFib('single')\r\nnumDouble = goldFib('double')\r\n%%\r\n% You'll notice that on line 7 of |goldFib|, we calculate the relative\r\n% accuracy for the golden mean in the correct precision.  You can see the\r\n% values here.\r\nTolSingle = eps(GoldenMeanSingle)\r\nTolDouble = eps(GoldenMeanDouble)\r\n%% Tools in MATLAB for Writing \"Generic\" Floating Point Programs\r\n% MATLAB has tools so you can create programs that work correctly on both\r\n% single and double precision.  You can see with this example that we only\r\n% needed to modify a small number of lines and terms in the M-file in order\r\n% to convert the file from handling double precision only to being able to\r\n% handle both single and double precision calculations appropriately.  Do\r\n% you need to do something similar?  Is it because you have large datasets\r\n% and use single precision to help manage the memory?  \r\n% <http:?p=38\/Respond Let me know>.\r\n\r\n\r\n##### SOURCE END #####\r\n-->","protected":false},"excerpt":{"rendered":"<p>\r\n   \r\n      How do you write M-files in MATLAB that you would like to have work correctly whether the inputs are double precision or single?\r\n         By correctly, I mean that the program gives an... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/loren\/2006\/05\/24\/programming-for-multiple-datatypes\/\">read more >><\/a><\/p>","protected":false},"author":39,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[16,6,11],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/38"}],"collection":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/users\/39"}],"replies":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/comments?post=38"}],"version-history":[{"count":3,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/38\/revisions"}],"predecessor-version":[{"id":3212,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/38\/revisions\/3212"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/media?parent=38"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/categories?post=38"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/tags?post=38"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}