<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:georss='http://www.georss.org/georss' xmlns:gd='http://schemas.google.com/g/2005' xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-9218555604707336107</id><updated>2012-02-05T23:38:25.020-08:00</updated><title type='text'>Baum Dev Blog</title><subtitle type='html'>Computer Science, (Web-)Development and DSP</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://baumdevblog.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9218555604707336107/posts/default?max-results=100'/><link rel='alternate' type='text/html' href='http://baumdevblog.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>BaumBlogger</name><uri>http://www.blogger.com/profile/12668078702880913731</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>5</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>100</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-9218555604707336107.post-4791865736890694691</id><published>2010-11-15T09:03:00.000-08:00</published><updated>2010-11-15T10:07:48.539-08:00</updated><title type='text'>High precision floating-point arithmetic in MS Visual C++</title><content type='html'>In &lt;a href="http://baumdevblog.blogspot.com/2010/11/fast-kahan-summation-implementation-in.html"&gt;my article about Kahan floating-point summation&lt;/a&gt; I showed how high precision summing can be realized with high speed. There is another efficient way to do high precision floating-point arithmetic but it isn't supported by the common SIMD (Single Instruction Multiple Data) instruction sets. Nevertheless, it's accuracy is significantly higher!&lt;br /&gt;&lt;br /&gt;This posting is structured as follows: First I talk about "extended precision" in general, giving some historical information. In the second part I show how and when extended precision can be used in VC++ without assembler. In the third part I show some assembler code and do the accuracy and speed evaluation.&lt;br /&gt;&lt;br /&gt;It all starts with the old x87 floating point (co-)processor. It's architecture contained the nowadays somewhat exotic datatype "extended precision" with 80bit size (64bit mantissa and 16bit exponent) and I guess it was created to have temporary variables with more-than-double precision in order to counteract too much rounding errors in double variables.&lt;br /&gt;&lt;br /&gt;It is this datatape that is commonly associated with "long double" variables but in MSVC++, long double is the same as double. Extended precision is not supported by the current implementation. There is a compiler switch to enable high precision math (&lt;a href="http://msdn.microsoft.com/en-us/library/aa289157%28VS.71%29.aspx#floapoint_topic2"&gt;-fp:precise&lt;/a&gt;) but this will not enable 80 bit math as one would like, sometimes. However, the Microsoft compiler can &lt;i&gt;calculate&lt;/i&gt; in 80bit but &lt;i&gt;not store&lt;/i&gt; results in 80 bits!&lt;br /&gt;&lt;br /&gt;Let's take a simple for loop as example:&lt;br /&gt;&lt;pre&gt;double sum = 0.0;&lt;br /&gt;for(int i=0;i&amp;lt;1000;i++)&lt;br /&gt;    sum += 0.1;&lt;/pre&gt;&lt;br /&gt;Ideally, sum would be held in 80 bits until the for-loop terminates and only then the results were written back into the double variable.&lt;br /&gt;&lt;br /&gt;Unfortunately, with the default MSVC++ compiler, each assignment results in a down-cast to double. This is to ensure portability because doing these kinds of optimization can easily change the behavior of some applications.&lt;br /&gt;&lt;br /&gt;So when does MSVC++ use 80bits precision? The answer in this case is simple. If the code was&lt;br /&gt;&lt;pre&gt;double sum = 0.1 + 0.1 /* + .... (1000 times!)*/;&lt;/pre&gt;&lt;br /&gt;the calculations would have been done in 80 bits, &lt;b&gt;if&lt;/b&gt; the &lt;i&gt;80bit-precision control bit of the processor&lt;/i&gt; was set. The number 0.1 as a literal however, would have been represented in 64 bits and then converted before processing. This is because there is no 80bit datatype at all neither for constants nor for variables. Generally speaking, all &lt;i&gt;intermediate expressions&lt;/i&gt; are evaluated at &lt;i&gt;register precision&lt;/i&gt; which means that all results without assignments and casts will be done in the fpu of the cpu and whatever precision is set on that will be used. However, it is guaranteed that this precision is &lt;i&gt;at least&lt;/i&gt; double when you work with doubles.&lt;br /&gt;&lt;br /&gt;So when exactly is this useful?&lt;br /&gt;Take for example the implementation of a musical IIR filter (acts like an equalizer on a stereo):&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;void iir(double* signal, int samples) {&lt;br /&gt;    double x0, x1, x2; // memorizes recent signal values&lt;br /&gt;    double y0, y1, y2; // memorizes recent output values&lt;br /&gt;    for(int i=0;i&amp;amp;samples;i++){&lt;br /&gt;        y2 = y1; y1 = y0; // shifts memory forward&lt;br /&gt;        x2 = x1; x1 = x0; // ..&lt;br /&gt;        x0 = samples[i];&lt;br /&gt;        y0 = x0 + 2 * x1 + x2          // &amp;lt;-- filter operation&lt;br /&gt;             - (1.5 * y1 - 1.45 * y2); // &amp;lt;-- &lt;br /&gt;        samples[i] = y0; // store result in signal array&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;This code is accuracy critical and contains a cumbersome statement with floating-point calculations. Some people might prefer to split this to two statements for cosmetic reasons, but this will remove accuracy because results are rounded to double three times instead of one!&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;y0 = x0 + 2 * x1 + x2;&lt;br /&gt;y0 -= 1.5 * y1 - 1.45 * y2;&lt;br /&gt;// this is the same as&lt;br /&gt;y0 = (double)(x0 + 2 * x1 + x2) &lt;br /&gt;   - (double)(1.5 * y1 - 1.45 * y2);&lt;br /&gt;// and  NOT&lt;br /&gt;y0 = (x0 + 2 * x1 + x2)&lt;br /&gt;   - (1.5 * y1 - 1.45 * y2);&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;But wait again! Does this do the trick already? The answer is no, it doesn't. At least not if you want to be sure that it works. To guarantee accurate results, the processor precision bit has to be set and the compiler has to be advised not to optimize so much that the code doesn't work anymore.&lt;br /&gt;&lt;br /&gt;First, the compiler pragma "#pragma fenv_access( [ on  | off ] )" has to tell the compiler that we will change processor flags and he should not optimize this away. Secondly, we need to use "_controlfp_s" to enable the high-precision bit of the processor:&lt;br /&gt;&lt;pre&gt;#include &amp;lt;float.h&amp;gt;&lt;br /&gt;#pragma fenv_access( on )&lt;br /&gt;void iir(double* signal, int samples) {&lt;br /&gt;&lt;br /&gt;    // enable 64 mantissa and store old settings&lt;br /&gt;    unsigned int control_word;&lt;br /&gt;    _controlfp_s(&amp;amp;control_word, _PC_64, MCW_PC);&lt;br /&gt;&lt;br /&gt;    // do calculations ...&lt;br /&gt;&lt;br /&gt;    // restores old processor settings&lt;br /&gt;    _controlfp_s(&amp;amp;control_word, _CW_DEFAULT, MCW_PC);&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;This is a nice way to avoid assembler in your code, but sometimes it just doesn't work. For example when you want to sum the elements of an array and you can not put it all in one statement. In this case it would be nice to use intrinsics but the necessary floating point operations are not (yet) available as intrinsics.&lt;br /&gt;&lt;br /&gt;So here is the assembler routine to sum array elements with extended precision:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;#include &amp;lt;float.h&amp;gt;&lt;br /&gt;#pragma fenv_access( on  )&lt;br /&gt;double sumEP(const double* a, int length)&lt;br /&gt;{&lt;br /&gt; if(length == 0)return 0.0;else if(length == 1)return a[0];&lt;br /&gt; &lt;br /&gt; double result;&lt;br /&gt; int i = length - 1;&lt;br /&gt;&lt;br /&gt; unsigned int control_word;&lt;br /&gt; _controlfp_s(&amp;amp;control_word, _PC_64, MCW_PC);&lt;br /&gt;&lt;br /&gt; _asm {&lt;br /&gt;  lea  eax, DWORD PTR a      ; load adress of a&lt;br /&gt;  mov  eax, [eax]&lt;br /&gt;  fld  QWORD ptr [eax]       ; load first value of a&lt;br /&gt;&lt;br /&gt;  mov  ecx, dword ptr i      ; load loop counter i&lt;br /&gt;&lt;br /&gt;loopStart:&lt;br /&gt;  sub  ecx, 1                ; i--&lt;br /&gt;  cmp  ecx, 0                ; if(i &amp;lt; 0) goto saveResults&lt;br /&gt;  jl   saveResults&lt;br /&gt;&lt;br /&gt;  add  eax, 8                ; go to next array element&lt;br /&gt;  fld  QWORD ptr [eax]       ; push a[i]&lt;br /&gt;  fadd                       ; add top two stack numbers&lt;br /&gt;  &lt;br /&gt;  jmp loopStart&lt;br /&gt;&lt;br /&gt;saveResults:&lt;br /&gt;  lea  eax, DWORD PTR result ; load address if result&lt;br /&gt;  fstp QWORD PTR [eax]       ; store result&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt; _controlfp_s(&amp;amp;control_word,_CW_DEFAULT, 0xfffff);&lt;br /&gt;&lt;br /&gt; return result;&lt;br /&gt;}&lt;/pre&gt;Calculating 10000000 times + 0.1 gave the following time and precision values:  &lt;br /&gt;&lt;table&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td&gt;&lt;/td&gt;&lt;td&gt;error&lt;/td&gt;&lt;td&gt;time&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;standard&lt;/td&gt;&lt;td&gt;-1.6E-4&lt;/td&gt;&lt;td&gt;1&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;SSE&lt;/td&gt;&lt;td&gt;-8.9E-5&lt;/td&gt;&lt;td&gt;0.97&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;extended&lt;/td&gt;&lt;td&gt;8.7E-8&lt;/td&gt;&lt;td&gt;0.97&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;Kahan/SSE&lt;/td&gt;&lt;td&gt;0&lt;/td&gt;&lt;td&gt;1.66&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;br /&gt;Calculating the sum over the first 10000000 elements in a geometric progression with q=0.9999:  &lt;br /&gt;&lt;table&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td&gt;&lt;/td&gt;&lt;td&gt;error&lt;/td&gt;&lt;td&gt;time&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;standard&lt;/td&gt;&lt;td&gt;1.4E-9&lt;/td&gt;&lt;td&gt;1&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;SSE&lt;/td&gt;&lt;td&gt;-1.7E-9&lt;/td&gt;&lt;td&gt;0.48&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;extended&lt;/td&gt;&lt;td&gt;1.5E-9&lt;/td&gt;&lt;td&gt;0.73&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;Kahan/SSE&lt;/td&gt;&lt;td&gt;1.5E-9&lt;/td&gt;&lt;td&gt;4.8&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;br /&gt;The tables show two things. In the first example, the precision depends highly on the calculation precision. The performance however is nearly the same for all approaches.&lt;br /&gt;The second example shows little to no difference in precision but in speed. I think the reason is, that in the second example the double precision summands are limiting the quality, but since the cpu can't optimize a lot, the runtime in this table is more relevant. In the first example the worst case accuracy is captured better but the runtime is not very helpful since all numbers equal 0.1.&lt;br /&gt;&lt;br /&gt;Notice that in contrast to my earlier posting, kahan is slower than standard summation. This is due to better compiler optimization in this post. Notice, that SSE Kahan is still faster than non-SSE kahan.&lt;br /&gt;&lt;br /&gt;The nice thing about VC++ is that if you only want higher precision for intermediate results, you can easily remove casts and set the processor accuracy bit.&lt;br /&gt;&lt;br /&gt;Hope you enjoyed this posting. Let me say that it's a pity that this is not usable with SSE1-4 so far. You'd have to compromise speed against precision if you use it, which is perfectly fine if double is accurate enough. &lt;br /&gt;&lt;br /&gt;Regards!&lt;div class="blogger-post-footer"&gt;&lt;script src="http://www.google-analytics.com/urchin.js" type="text/javascript"&gt;
&lt;/script&gt;
&lt;script type="text/javascript"&gt;
_uacct = "UA-1434537-1";
urchinTracker();
&lt;/script&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9218555604707336107-4791865736890694691?l=baumdevblog.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://baumdevblog.blogspot.com/feeds/4791865736890694691/comments/default' title='Kommentare zum Post'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=9218555604707336107&amp;postID=4791865736890694691' title='0 Kommentare'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9218555604707336107/posts/default/4791865736890694691'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9218555604707336107/posts/default/4791865736890694691'/><link rel='alternate' type='text/html' href='http://baumdevblog.blogspot.com/2010/11/high-precision-floating-point.html' title='High precision floating-point arithmetic in MS Visual C++'/><author><name>BaumBlogger</name><uri>http://www.blogger.com/profile/12668078702880913731</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9218555604707336107.post-1014172109344373801</id><published>2010-11-04T11:27:00.000-07:00</published><updated>2010-11-04T15:52:14.269-07:00</updated><title type='text'>Butterworth Lowpass Filter Coefficients in C++</title><content type='html'>When I searched the web it wasn't easy to find a simple function to calculate Butterworth lowpass filter coefficients, so I looked up the theory and did things on my own.&lt;br /&gt;&lt;br /&gt;If you just want coefficients for a single filter specification, you can use the code generated by &lt;a href="http://www-users.cs.york.ac.uk/%7Efisher/mkfilter/"&gt;this nice online code generator&lt;/a&gt;. It will produce C-code that you can use for a specified samplerate and cutoff-frequency. It will also do Chebyshev and Bessel filters as well as lowpass, highpass, bandpass and bandstop filters for you.&lt;br /&gt;&lt;br /&gt;However, if your program needs adjustable cutoff or samplerate, you can not use this script.&lt;br /&gt;&lt;br /&gt;The &lt;span style="font-style:italic;"&gt;first part&lt;/span&gt; of this post will take a glance at the required analytical steps and the &lt;span style="font-style:italic;"&gt;second part&lt;/span&gt; will simply give you the code.&lt;br /&gt;&lt;br /&gt;One of the standard techniques is to use the analytical frequency response of the filter and then use &lt;a href="http://en.wikipedia.org/wiki/Bilinear_transform"&gt;bilinear transformation&lt;/a&gt; to obtain IIR filter coefficients.&lt;br /&gt;&lt;br /&gt;The required steps require some math for which I found &lt;a href="http://il.youtube.com/watch?v=5RoPKr94_-w"&gt;this lecture&lt;/a&gt; very helpful:&lt;br /&gt;&lt;br /&gt;1) Take analytical transfer function: H(s)&lt;br /&gt;2) Do bilinear transform: H( (z-1)/(z+1) )&lt;br /&gt;3) "Warp" cutoff frequency to find cutoff in the "bilinear domain"&lt;br /&gt;4) Express function as &lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://upload.wikimedia.org/math/c/e/a/cea9aeb4bbf5f4312211e65473147c11.png"&gt;&lt;img style="cursor: pointer; width: 427px; height: 49px;" src="http://upload.wikimedia.org/math/c/e/a/cea9aeb4bbf5f4312211e65473147c11.png" alt="" border="0" /&gt;&lt;/a&gt;&lt;br /&gt;5) Use these coefficients for time-domain filtering with the &lt;a href="http://en.wikipedia.org/wiki/Digital_filter#Difference_equation"&gt;linear difference equation&lt;/a&gt;: &lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://upload.wikimedia.org/math/7/5/5/7550fd7e8b5e1aa43d587ff986ef5238.png"&gt;&lt;img style="cursor:pointer; cursor:hand;width: 330px; height: 52px;" src="http://upload.wikimedia.org/math/7/5/5/7550fd7e8b5e1aa43d587ff986ef5238.png" border="0" alt="" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Notice that in order to simplify the derivation of the filter, you can safely set the sample time T to 2.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Doing this for a 2 pole Butterworth filter gives the following code in C++:&lt;br /&gt;&lt;br /&gt;&lt;pre style="font-size: small;"&gt;&lt;br /&gt;void getLPCoefficientsButterworth2Pole(const int samplerate, const double cutoff, double* const ax, double* const by)&lt;br /&gt;{&lt;br /&gt;    double PI      = 3.1415926535897932385;&lt;br /&gt;    double sqrt2 = 1.4142135623730950488;&lt;br /&gt;&lt;br /&gt;    double QcRaw  = (2 * PI * cutoff) / samplerate; // Find cutoff frequency in [0..PI]&lt;br /&gt;    double QcWarp = tan(QcRaw); // Warp cutoff frequency&lt;br /&gt;&lt;br /&gt;    double gain = 1 / (1+sqrt2/QcWarp + 2/(QcWarp*QcWarp));&lt;br /&gt;    by[2] = (1 - sqrt2/QcWarp + 2/(QcWarp*QcWarp)) * gain;&lt;br /&gt;    by[1] = (2 - 2 * 2/(QcWarp*QcWarp)) * gain;&lt;br /&gt;    by[0] = 1;&lt;br /&gt;    ax[0] = 1 * gain;&lt;br /&gt;    ax[1] = 2 * gain;&lt;br /&gt;    ax[2] = 1 * gain;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;which then can be used in a filter like this:&lt;br /&gt;&lt;br /&gt;&lt;pre style="font-size: small;"&gt;&lt;br /&gt;double xv[3];&lt;br /&gt;double yv[3];&lt;br /&gt;&lt;br /&gt;void filter(double* samples, int count)&lt;br /&gt;{&lt;br /&gt;   double ax[3];&lt;br /&gt;   double by[3];&lt;br /&gt;&lt;br /&gt;   getLPCoefficientsButterworth2Pole(44100, 5000, ax, by);&lt;br /&gt;&lt;br /&gt;   for (int i=0;i&amp;lt;count;i++)&lt;br /&gt;   {&lt;br /&gt;       xv[2] = xv[1]; xv[1] = xv[0];&lt;br /&gt;       xv[0] = samples[i];&lt;br /&gt;       yv[2] = yv[1]; yv[1] = yv[0];&lt;br /&gt;&lt;br /&gt;       yv[0] =   (ax[0] * xv[0] + ax[1] * xv[1] + ax[2] * xv[2]&lt;br /&gt;                    - by[1] * yv[0]&lt;br /&gt;                    - by[2] * yv[1]);&lt;br /&gt;&lt;br /&gt;       samples[i] = yv[0];&lt;br /&gt;   }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;And that is it. To reduce summation error you may want to use &lt;a href="http://baumdevblog.blogspot.com/2010/11/fast-kahan-summation-implementation-in.html"&gt;Kahan summation&lt;/a&gt;!&lt;div class="blogger-post-footer"&gt;&lt;script src="http://www.google-analytics.com/urchin.js" type="text/javascript"&gt;
&lt;/script&gt;
&lt;script type="text/javascript"&gt;
_uacct = "UA-1434537-1";
urchinTracker();
&lt;/script&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9218555604707336107-1014172109344373801?l=baumdevblog.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://baumdevblog.blogspot.com/feeds/1014172109344373801/comments/default' title='Kommentare zum Post'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=9218555604707336107&amp;postID=1014172109344373801' title='3 Kommentare'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9218555604707336107/posts/default/1014172109344373801'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9218555604707336107/posts/default/1014172109344373801'/><link rel='alternate' type='text/html' href='http://baumdevblog.blogspot.com/2010/11/butterworth-lowpass-filter-coefficients.html' title='Butterworth Lowpass Filter Coefficients in C++'/><author><name>BaumBlogger</name><uri>http://www.blogger.com/profile/12668078702880913731</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9218555604707336107.post-4639787122026371054</id><published>2010-11-01T11:03:00.000-07:00</published><updated>2010-11-01T12:50:55.153-07:00</updated><title type='text'>Fast Kahan summation implementation in Assembler</title><content type='html'>Summing floating-point numbers is trickier than most people think. For example ((x+y)+z) does not necessarily equal (x+(y+z)) with FP numbers. Also, it is easy to loose precision if two numbers of different magnitude are summed.&lt;br /&gt;&lt;br /&gt;If you want to add several floating-point numbers, these rounding errors may sum up and make the result unusable.&lt;br /&gt;&lt;br /&gt;Luckily, there is help on the way and it is called &lt;a href="http://en.wikipedia.org/wiki/Kahan_summation_algorithm"&gt;"Kahan Summation"&lt;/a&gt;.&lt;br /&gt;The basic idea is to introduce an extra error variable that remembers the errors made, so that at a later point, when the error has accumulated, it can be subtracted. Useful advice and other methods are described in &lt;a href="http://www.drdobbs.com/184403224"&gt;here&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;The common C++-code for this operation looks something like this:&lt;br /&gt;&lt;br /&gt;&lt;pre style="font-size: small;"&gt;&lt;br /&gt;double sum(const double* a, int length)&lt;br /&gt;{&lt;br /&gt;    if(length == 0)&lt;br /&gt;        return 0.0;&lt;br /&gt;    &lt;br /&gt;    double result = a[0];&lt;br /&gt;    double error = 0.0;&lt;br /&gt;    for(int i=1;i&amp;lt;length;i++)&lt;br /&gt;    {&lt;br /&gt;        double tmpA = a[i] - error;&lt;br /&gt;        double tmpSum = result + tmpA;&lt;br /&gt;        error = (tmpSum - result) - tmpA;&lt;br /&gt;        result = tmpSum;&lt;br /&gt;    }&lt;br /&gt;    &lt;br /&gt;    return result;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Compared to normal summing with a simple for loop, this implementation is a few times slower. Even worse, turning on compiler optimizations may destroy the whole function because "error = (tmpSum - result) - tmpA" could be reduced to "error = 0". So there must be a way to stop the compiler from doing &lt;span style="font-style: italic;"&gt;certain&lt;/span&gt; optimizations but not doing others.&lt;br /&gt;&lt;br /&gt;That is hard.&lt;br /&gt;&lt;br /&gt;So I decided to write it in Assembler. With SSE2 I could process two double values at a time which is a pretty good optimization which even good compilers may not find. Because my solution uses inline assembler, it will not be optimized any further and the functionality remains intact.&lt;br /&gt;&lt;br /&gt;Here it comes:&lt;br /&gt;&lt;br /&gt;&lt;pre style="font-size: small;"&gt;&lt;br /&gt;double sum(const double* a, int length)&lt;br /&gt;{&lt;br /&gt;    if(length == 0)&lt;br /&gt;        return 0.0;&lt;br /&gt;    else if(length == 1)&lt;br /&gt;        return a[0];&lt;br /&gt;    &lt;br /&gt;    double result1 = 0.0;&lt;br /&gt;    double result2 = 0.0;&lt;br /&gt;    double error1 = 0.0;&lt;br /&gt;    double error2 = 0.0;&lt;br /&gt;&lt;br /&gt;    int i = length - 2;&lt;br /&gt;&lt;br /&gt;    _asm {&lt;br /&gt;        xorps     xmm6, xmm6              ; Initialize error register (xmm6)&lt;br /&gt;&lt;br /&gt;        mov     eax, DWORD PTR a            ; Initialize result register (xmm4)&lt;br /&gt;        movhpd     xmm4, QWORD PTR [eax]&lt;br /&gt;        movlpd     xmm4, QWORD PTR [eax+8]&lt;br /&gt;&lt;br /&gt;        mov      ecx, dword ptr i        ; ecx = i save loop counter&lt;br /&gt;&lt;br /&gt;loopStart:&lt;br /&gt;        sub        ecx, 2                    ; ecx -= 2&lt;br /&gt;        cmp     ecx,0                ; if(ecx &lt;= 0) goto saveResults&lt;br /&gt;        jl     saveResults&lt;br /&gt;&lt;br /&gt;        add        eax, 16                    ; go to next two array elements&lt;br /&gt;        movhpd     xmm0, QWORD PTR [eax]&lt;br /&gt;        movlpd     xmm0, QWORD PTR [eax+8]; Save a[2*i], a[2*i+1] in xmm0&lt;br /&gt;&lt;br /&gt;        subpd    xmm0, xmm6                ; a = a[i] - error&lt;br /&gt;&lt;br /&gt;        movapd    xmm1, xmm4                ; ts = result + a&lt;br /&gt;        addpd    xmm1, xmm0                &lt;br /&gt;&lt;br /&gt;        movapd    xmm6, xmm1                ; error = (ts - result) - a&lt;br /&gt;        subpd    xmm6, xmm4&lt;br /&gt;        subpd    xmm6, xmm0                &lt;br /&gt;&lt;br /&gt;        movapd    xmm4, xmm1                ; result = ts&lt;br /&gt;        &lt;br /&gt;        jmp loopStart&lt;br /&gt;&lt;br /&gt;saveResults:&lt;br /&gt;        movhpd     result1, xmm4 ; Save result into result variables&lt;br /&gt;        movlpd     result2, xmm4&lt;br /&gt;        mov      dword ptr i, ecx&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    if(i == -1)&lt;br /&gt;    {&lt;br /&gt;        double tmpA = a[length-1] - error1;&lt;br /&gt;        double tmpSum = result1 + tmpA;&lt;br /&gt;        error1 = (tmpSum - result1) - tmpA;&lt;br /&gt;        result1 = tmpSum;&lt;br /&gt;    }&lt;br /&gt;    &lt;br /&gt;    return (result1+result2)-(error1+error2);&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The performance on my Intel(R) Core(TM)2 Duo T8300 was as follows:&lt;br /&gt;&lt;table&gt;&lt;tr&gt;&lt;td&gt;Standard sum&lt;/td&gt;&lt;td&gt;1x&lt;/td&gt;&lt;/tr&gt;&lt;br /&gt;&lt;tr&gt;&lt;td&gt;Standard sum (floats)&lt;/td&gt;&lt;td&gt;1.6x&lt;/td&gt;&lt;/tr&gt;&lt;br /&gt;&lt;tr&gt;&lt;td&gt;Kahan&lt;/td&gt;&lt;td&gt;3.2x&lt;/td&gt;&lt;/tr&gt;&lt;br /&gt;&lt;tr&gt;&lt;td&gt;Kahan SSE2&lt;/td&gt;&lt;td&gt;0.9x&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;&lt;br /&gt;&lt;br /&gt;As can be seen from the numbers, on my cpu the optimized code is three times faster and even faster than a normal unoptimized for loop. I am happy do discuss any requests and complaints. Simple summing with SSE would have been possible as well but that has the accuracy problems mentioned earlier.&lt;div class="blogger-post-footer"&gt;&lt;script src="http://www.google-analytics.com/urchin.js" type="text/javascript"&gt;
&lt;/script&gt;
&lt;script type="text/javascript"&gt;
_uacct = "UA-1434537-1";
urchinTracker();
&lt;/script&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9218555604707336107-4639787122026371054?l=baumdevblog.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://baumdevblog.blogspot.com/feeds/4639787122026371054/comments/default' title='Kommentare zum Post'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=9218555604707336107&amp;postID=4639787122026371054' title='5 Kommentare'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9218555604707336107/posts/default/4639787122026371054'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9218555604707336107/posts/default/4639787122026371054'/><link rel='alternate' type='text/html' href='http://baumdevblog.blogspot.com/2010/11/fast-kahan-summation-implementation-in.html' title='Fast Kahan summation implementation in Assembler'/><author><name>BaumBlogger</name><uri>http://www.blogger.com/profile/12668078702880913731</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>5</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9218555604707336107.post-3204401974378343526</id><published>2007-04-26T16:04:00.000-07:00</published><updated>2007-04-26T16:10:09.460-07:00</updated><title type='text'>Python design by contract</title><content type='html'>Today I've implemented some decorators for Eiffel-like design py contract.&lt;br /&gt;It's very nice to use I think:&lt;br /&gt;&lt;br /&gt;&lt;blockquote&gt;@require('s1 != 0')&lt;br /&gt;def inv(s1): return 1/s1&lt;/blockquote&gt;&lt;br /&gt;or&lt;br /&gt;&lt;blockquote&gt;@require('x != 0')&lt;br /&gt;@enshure('result &gt; 0')&lt;br /&gt;def quad(x): return x*x*x / x&lt;/blockquote&gt;&lt;br /&gt;&lt;br /&gt;For more information just ask me. I'll put the code somewhere, soon.&lt;br /&gt;&lt;br /&gt;- stanz&lt;div class="blogger-post-footer"&gt;&lt;script src="http://www.google-analytics.com/urchin.js" type="text/javascript"&gt;
&lt;/script&gt;
&lt;script type="text/javascript"&gt;
_uacct = "UA-1434537-1";
urchinTracker();
&lt;/script&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9218555604707336107-3204401974378343526?l=baumdevblog.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://baumdevblog.blogspot.com/feeds/3204401974378343526/comments/default' title='Kommentare zum Post'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=9218555604707336107&amp;postID=3204401974378343526' title='0 Kommentare'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9218555604707336107/posts/default/3204401974378343526'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9218555604707336107/posts/default/3204401974378343526'/><link rel='alternate' type='text/html' href='http://baumdevblog.blogspot.com/2007/04/python-design-by-contract.html' title='Python design by contract'/><author><name>BaumBlogger</name><uri>http://www.blogger.com/profile/12668078702880913731</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9218555604707336107.post-8661753355127769339</id><published>2007-02-28T14:29:00.000-08:00</published><updated>2007-03-01T05:30:44.357-08:00</updated><title type='text'>Profiling Django: hotshot</title><content type='html'>Today I've discovered an article about &lt;a href="http://www.rkblog.rk.edu.pl/w/p/django-profiling-hotshot-and-kcachegrind/"&gt;profiling Django&lt;/a&gt; with hotshot. After some minutes of googling 'hotspot' I recognized my fault and found the right python &lt;a href="http://docs.python.org/lib/module-hotshot.html"&gt;doc&lt;/a&gt;.&lt;br /&gt;As I didn't want to setup my apache just for a little profiling session, I did the following:&lt;br /&gt;to settings.py I've added&lt;br /&gt;&lt;blockquote&gt;import hotshot&lt;br /&gt;PROF = hotshot.Profile("plik.prof")&lt;/blockquote&gt;every view-method that should be profiled got:&lt;br /&gt;&lt;blockquote&gt;from settings import PROF&lt;br /&gt;PROF.start()&lt;br /&gt;(...)&lt;br /&gt;PROF.stop()&lt;/blockquote&gt;&lt;br /&gt;and finally this came to my 'viewstat'-view:&lt;br /&gt;&lt;blockquote&gt;import hotshot.stats&lt;br /&gt;stats = hotshot.stats.load("plik.prof")&lt;br /&gt;stats.strip_dirs()&lt;br /&gt;stats.sort_stats('time', 'calls')&lt;br /&gt;stats.print_stats(20)&lt;/blockquote&gt;&lt;br /&gt;And that's how I've become happy today. Wish me good luck for my cold.&lt;br /&gt;- baum&lt;br /&gt;&lt;br /&gt;It's fair to say that this probably won't run in a production-setup because of multithreading.&lt;br /&gt;&lt;br /&gt;&lt;blockquote style="font-family: times new roman; color: rgb(0, 0, 0);"&gt;&lt;/blockquote&gt;&lt;br /&gt;&lt;br /&gt;&lt;blockquote style="font-family: times new roman; color: rgb(0, 0, 0);"&gt;&lt;/blockquote&gt;&lt;span class="" style="display: block; color: rgb(0, 0, 0);font-family:times new roman;" id="formatbar_CreateLink" title="" link="" onmouseover="ButtonHoverOn(this);" onmouseout="ButtonHoverOff(this);" onmouseup="" onmousedown="CheckFormatting(event);FormatbarButton('richeditorframe', this, 8);ButtonMouseDown(this);" &gt;&lt;/span&gt;&lt;div class="blogger-post-footer"&gt;&lt;script src="http://www.google-analytics.com/urchin.js" type="text/javascript"&gt;
&lt;/script&gt;
&lt;script type="text/javascript"&gt;
_uacct = "UA-1434537-1";
urchinTracker();
&lt;/script&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9218555604707336107-8661753355127769339?l=baumdevblog.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://baumdevblog.blogspot.com/feeds/8661753355127769339/comments/default' title='Kommentare zum Post'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=9218555604707336107&amp;postID=8661753355127769339' title='0 Kommentare'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9218555604707336107/posts/default/8661753355127769339'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9218555604707336107/posts/default/8661753355127769339'/><link rel='alternate' type='text/html' href='http://baumdevblog.blogspot.com/2007/02/profiling-django-hotshot.html' title='Profiling Django: hotshot'/><author><name>BaumBlogger</name><uri>http://www.blogger.com/profile/12668078702880913731</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry></feed>
