Shared posts

05 Jun 18:15

GotW #91 Solution: Smart Pointer Parameters

by Herb Sutter

NOTE: Last year, I posted three new GotWs numbered #103-105. I decided leaving a gap in the numbers wasn’t best after all, so I am renumbering them to #89-91 to continue the sequence. Here is the updated version of what was GotW #105.

How should you prefer to pass smart pointers, and why?

Problem

JG Question

1. What are the performance implications of the following function declaration? Explain.

void f( shared_ptr<widget> );

Guru Questions

2. What are the correctness implications of the function declaration in #1? Explain with clear examples.

3. A colleague is writing a function f that takes an existing object of type widget as a required input-only parameter, and trying to decide among the following basic ways to take the parameter (omitting const):

void f( widget* );              (a)
void f( widget& );              (b)
void f( unique_ptr<widget> );   (c)
void f( unique_ptr<widget>& );  (d)
void f( shared_ptr<widget> );   (e)
void f( shared_ptr<widget>& );  (f)

Under what circumstances is each appropriate? Explain your answer, including where const should or should not be added anywhere in the parameter type.

(There are other ways to pass the parameter, but we will consider only the ones shown above.)

Solution

1. What are the performance implications of the following function declaration? Explain.

void f( shared_ptr<widget> );

A shared_ptr stores strong and weak reference counts (see GotW #89). When you pass by value, you have to copy the argument (usually) on entry to the function, and then destroy it (always) on function exit. Let’s dig into what this means.

When you enter the function, the shared_ptr is copy-constructed, and this requires incrementing the strong reference count. (Yes, if the caller passes a temporary shared_ptr, you move-construct and so don’t have to update the count. But: (a) it’s quite rare to get a temporary shared_ptr in normal code, other than taking one function’s return value and immediately passing that to a second function; and (b) besides as we’ll see most of the expense is on the destruction of the parameter anyway.)

When exiting the function, the shared_ptr is destroyed, and this requires decrementing its internal reference count.

What’s so bad about a “shared reference count increment and decrement?” Two things, one related to the “shared reference count” and one related to the “increment and decrement.” It’s good to be aware of how this can incur performance costs for two reasons: one major and common, and one less likely in well-designed code and so probably more minor.

First, the major reason is the performance cost of the “increment and decrement”: Because the reference count is an atomic shared variable (or equivalent), incrementing and decrementing it are internally-synchronized read-modify-write shared memory operations.

Second, the less-likely minor reason is the potentially scalability-bustingly contentious nature of the “shared reference count”: Both increment and decrement update the reference count, which means that at the processor and memory level only one core at a time can be executing such an instruction on the same reference count because it needs exclusive access to the count’s cache line. The net result is that this causes some contention on the count’s cache line, which can affect scalability if it’s a popular cache line being touched by multiple threads in tight loops—such as if two threads are calling functions like this one in tight loops and accessing shared_ptrs that own the same object. “So don’t do that, thou heretic caller!” we might righteously say. Well and good, but the caller doesn’t always know when two shared_ptrs used on two different threads refer to the same object, so let’s not be quick to pile the wood around his stake just yet.

As we will see, an essential best practice for any reference-counted smart pointer type is to avoid copying it unless you really mean to add a new reference. This cannot be stressed enough. This directly addresses both of these costs and pushes their performance impact down into the noise for most applications, and especially eliminates the second cost because it is an antipattern to add and remove references in tight loops.

At this point, we will be tempted to solve the problem by passing the shared_ptr by reference. But is that really the right thing to do? It depends.

2. What are the correctness implications of the function declaration in #1?

The only correctness implication is that the function advertises in a clear type-enforced way that it will (or could) retain a copy of the shared_ptr.

That this is the only correctness implication might surprise some people, because there would seem to be one other major correctness benefit to taking a copy of the argument, namely lifetime: Assuming the pointer is not already null, taking a copy of the shared_ptr guarantees that the function itself holds a strong refcount on the owned object, and that therefore the object will remain alive for the duration of the function body, or until the function itself chooses to modify its parameter.

However, we already get this for free—thanks to structured lifetimes, the called function’s lifetime is a strict subset of the calling function’s call expression. Even if we passed the shared_ptr by reference, our function would as good as hold a strong refcount because the caller already has one—he passed us the shared_ptr in the first place, and won’t release it until we return. (Note this assumes the pointer is not aliased. You have to be careful if the smart pointer parameter could be aliased, but in this respect it’s no different than any other aliased object.)

Guideline: Don’t pass a smart pointer as a function parameter unless you want to use or manipulate the smart pointer itself, such as to share or transfer ownership.

Guideline: Prefer passing objects by value, *, or &, not by smart pointer.

If you’re saying, “hey, aren’t raw pointers evil?”, that’s excellent, because we’ll address that next.

3. A colleague is writing a function f that takes an existing object of type widget as a required input-only parameter, and trying to decide among the following basic ways to take the parameter (omitting const). Under what circumstances is each appropriate? Explain your answer, including where const should or should not be added anywhere in the parameter type.

(a) and (b): Prefer passing parameters by * or &.

void f( widget* );              (a)
void f( widget& );              (b)

These are the preferred way to pass normal object parameters, because they stay agnostic of whatever lifetime policy the caller happens to be using.

Non-owning raw * pointers and & references are okay to observe an object whose lifetime we know exceeds that of the pointer or reference, which is usually true for function parameters. Thanks to structured lifetimes, by default arguments passed to f in the caller outlive f‘s function call lifetime, which is extremely useful (not to mention efficient) and makes non-owning * and & appropriate for parameters.

Pass by * or & to accept a widget independently of how the caller is managing its lifetime. Most of the time, we don’t want to commit to a lifetime policy in the parameter type, such as requiring the object be held by a specific smart pointer, because this is usually needlessly restrictive. As usual, use a * if you need to express null (no widget), otherwise prefer to use a &; and if the object is input-only, write const widget* or const widget&.

(c) Passing unique_ptr by value means “sink.”

void f( unique_ptr<widget> );   (c)

This is the preferred way to express a widget-consuming function, also known as a “sink.”

Passing a unique_ptr by value is only possible by moving the object and its unique ownership from the caller to the callee. Any function like (c) takes ownership of the object away from the caller, and either destroys it or moves it onward to somewhere else.

Note that, unlike some of the other options below, this use of a by-value unique_ptr parameter actually doesn’t limit the kind of object that can be passed to those managed by a unique_ptr. Why not? Because any pointer can be explicitly converted to a unique_ptr. If we didn’t use a unique_ptr here we would still have to express “sink” semantics, just in a more brittle way such as by accepting a raw owning pointer (anathema!) and documenting the semantics in comments. Using (c) is vastly superior because it documents the semantics in code, and requires the caller to explicitly move ownership.

Consider the major alternative:

// Smelly 20th-century alternative
void bad_sink( widget* p );  // will destroy p; PLEASE READ THIS COMMENT

// Sweet self-documenting self-enforcing modern version (c)
void good_sink( unique_ptr<widget> p );

And how much better (c) is:

// Older calling code that calls the new good_sink is safer, because
// it's clearer in the calling code that ownership transfer is going on
// (this older code has an owning * which we shouldn't do in new code)
//
widget* pw = ... ; 

bad_sink ( pw );             // compiles: remember not to use pw again!

good_sink( pw );             // error: good
good_sink( unique_ptr<widget>{pw} );  // need explicit conversion: good

// Modern calling code that calls good_sink is safer, and cleaner too
//
unique_ptr<widget> pw = ... ;

bad_sink ( pw.get() );       // compiles: icky! doesn't reset pw
bad_sink ( pw.release() );   // compiles: must remember to use this way

good_sink( pw );             // error: good!
good_sink( move(pw) );       // compiles: crystal clear what's going on

Guideline: Express a “sink” function using a by-value unique_ptr parameter.

Because the callee will now own the object, usually there should be no const on the parameter because the const should be irrelevant.

(d) Passing unique_ptr by reference is for in/out unique_ptr parameters.

void f( unique_ptr<widget>& );  (d)

This should only be used to accept an in/out unique_ptr, when the function is supposed to actually accept an existing unique_ptr and potentially modify it to refer to a different object. It is a bad way to just accept a widget, because it is restricted to a particular lifetime strategy in the caller.

Guideline: Use a non-const unique_ptr& parameter only to modify the unique_ptr.

Passing a const unique_ptr<widget>& is strange because it can accept only either null or a widget whose lifetime happens to be managed in the calling code via a unique_ptr, and the callee generally shouldn’t care about the caller’s lifetime management choice. Passing widget* covers a strict superset of these cases and can accept “null or a widget” regardless of the lifetime policy the caller happens to be using.

Guideline: Don’t use a const unique_ptr& as a parameter; use widget* instead.

I mention widget* because that doesn’t change the (nullable) semantics; if you’re being tempted to pass const shared_ptr<widget>&, what you really meant was widget* which expresses the same information. If you additionally know it can’t be null, though, of course use widget&.

(e) Passing shared_ptr by value implies taking shared ownership.

void f( shared_ptr<widget> );   (e)

As we saw in #2, this is recommended only when the function wants to retain a copy of the shared_ptr and share ownership. In that case, a copy is needed anyway so the copying cost is fine. If the local scope is not the final destination, just std::move the shared_ptr onward to wherever it needs to go.

Guideline: Express that a function will store and share ownership of a heap object using a by-value shared_ptr parameter.

Otherwise, prefer passing a * or & (possibly to const) instead, since that doesn’t restrict the function to only objects that happen to be owned by shared_ptrs.

(f) Passing shared_ptr& is useful for in/out shared_ptr manipulation.

void f( shared_ptr<widget>& );  (f)

Similarly to (d), this should mainly be used to accept an in/out shared_ptr, when the function is supposed to actually modify the shared_ptr itself. It’s usually a bad way to accept a widget, because it is restricted to a particular lifetime strategy in the caller.

Note that per (e) we pass a shared_ptr by value if the function will share ownership. In the special case where the function might share ownership, but doesn’t necessarily take a copy of its parameter on a given call, then pass a const shared_ptr& to avoid the copy on the calls that don’t need it, and take a copy of the parameter if and when needed.

Guideline: Use a non-const shared_ptr& parameter only to modify the shared_ptr. Use a const shared_ptr& as a parameter only if you’re not sure whether or not you’ll take a copy and share ownership; otherwise use widget* instead (or if not nullable, a widget&).

Acknowledgments

Thanks in particular to the following for their feedback to improve this article: mttpd, zahirtezcan, Jon, GregM, Andrei Alexandrescu.


Filed under: GotW
05 Jun 06:27

Understanding basic motion calculations in games: Euler vs. Verlet

by sam

During the past month, I have found myself in the position of having to explain the contents of this article to six different persons, either at work or over the Internet. Though there are a lot of articles on the subject, it’s still as if almost everyone gets it wrong. I was still polishing this article when I had the opportunity to explain it ​a seventh time.

And two days ago a coworker told me the source code of a certain framework disagreed with me… The kind of framework that probably has three NDAs preventing me from even thinking about it.

Well that framework got it wrong, too. So now I’m mad at the entire world for no rational reason other than the ever occurring realisation of the amount of wrong out there, and this article is but a catharsis to deal with my uncontrollable rage.

A simple example

Imagine a particle with position Pos and velocity Vel affected by acceleration Accel. Let’s say for the moment that the acceleration is constant. This is the case when only gravity is present.

A typical game engine loop will update position with regards to a timestep (often the duration of a frame) using the following method, known as Euler integration:

Particle::Update(float dt)
{
    Accel = vec3(0, 0, -9.81); /* Constant acceleration: gravity */
    Vel = Vel + Accel * dt;    /* New, timestep-corrected velocity */
    Pos = Pos + Vel * dt;      /* New, timestep-corrected position */
}

This comes directly from the ​definition of acceleration:

\[a(t) = \frac{\mathrm{d}}{\mathrm{d}t}v(t)\]
\[v(t) = \frac{\mathrm{d}}{\mathrm{d}t}p(t)\]

Putting these two differential equations into Euler integration gives us the above code.

Measuring accuracy

Typical particle trajectories would look a bit like this:

These are three runs of the above simulation with the same initial values.

  • once with maximum accuracy,
  • once at 60 frames per second,
  • once at 30 frames per second.

You can notice the slight inaccuracy in the trajectories.

You may think…

“Oh, it could be worse; it’s just the expected inaccuracy with different framerate values.”

Well, no.

Just… no.

If you are updating positions this way and you do not have a really good reason for doing so then either you or the person who taught you is a fucking idiot and should not have been allowed to write so-called physics code in the first place and I most certainly hope to humbly bestow enlightenment upon you in the form of a massive cluebat and don’t you dare stop reading this sentence before I’m finished.

Why this is wrong

When doing ​kinematics, computing position from acceleration is an integration process. First you integrate acceleration with respect to time to get velocity, then you integrate velocity to get position.

\[v(t) = \int_0^t a(t)\,\mathrm{d}t\]
\[p(t) = \int_0^t v(t)\,\mathrm{d}t\]

The integral of a function can be seen as the area below its curve. So, how do you properly get the integral of our velocity between t and t + dt, ie. the green area below?

It’s not by doing new_velocity * dt (left image).

It’s not by doing old_velocity * dt either (middle image).

It’s obviously by doing (old_velocity + new_velocity) * 0.5 * dt (right image).

And now for the correct code

This is what the update method should look like. It’s called Velocity Verlet integration (not strictly the same as Verlet integration, but with a similar error order) and it always gives the perfect, exact position of the particle in the case of constant acceleration, even with the nastiest framerate you can think of. Even at two frames per second.

Particle::Update(float dt)
{
    Accel = vec3(0, 0, -9.81);
    vec3 OldVel = Vel;
    Vel = Vel + Accel * dt;
    Pos = Pos + (OldVel + Vel) * 0.5 * dt;
}

And the resulting trajectories at different framerates:

Further readings

“Oh wow thank you. But what if acceleration is not constant, like in real life?”

Well I am glad you asked.

​Euler integration and ​Verlet integration are part of a family of iterative methods known as the ​Runge-Kutta methods, respectively of first order and second order. There are many more for you to discover and study.

  • Richard Lord did this nice and instructive ​animated presentation about several integration methods.
  • Glenn Fiedler also explains in ​this article why idiots use Euler, and provides a nice introduction to RK4 together with source code.
  • Florian Boesch did a ​thorough coverage of various integration methods for the specific application of gravitation (it is one of the rare cases where Euler seems to actually perform better).

In practice, Verlet will still only give you an approximation of your particle’s position. But it will almost always be a much better approximation than Euler. If you need even more accuracy, look at the ​fourth-order Runge-Kutta (RK4) method. Your physics will suck a lot less, I guarantee it.

Acknowledgements

I would like to thank everyone cited in this article, explicitly or implicitly, as well as the commenters below who spotted mistakes and provided corrections or improvements.

04 Jun 14:02

The Security Risks of Unregulated Google Search

by schneier

Someday I need to write an essay on the security risks of secret algorithms that become part of our infrastructure. This paper gives one example of that. Could Google tip an election by manipulating what comes up from search results on the candidates?

The study’s participants, selected to resemble the US voting population, viewed the results for two candidates on a mock search engine called Kadoodle. By front-loading Kadoodle’s results with articles favoring one of the candidates, Epstein shifted enough of his participants' voter preferences toward the favored candidate to simulate the swing of a close election. But here’s the kicker: in one round of the study, Epstein configured Kadoodle so that it hid the manipulation from 100 percent of the participants.

Turns out that it could. And, it wouldn't even be illegal for Google to do it.

The author thinks that government regulation is the only reasonable solution.

Epstein believes that the mere existence of the power to fix election outcomes, wielded or not, is a threat to democracy, and he asserts that search engines should be regulated accordingly. But regulatory analogies for a many-armed, ever-shifting company like Google are tough to pin down. For those who see search results as a mere passive relaying of information, like a library index or a phone book, there is precedent for regulation. In the past, phone books -- with a monopoly on the flow of certain information to the public -- were prevented from not listing businesses even when paid to do so. In the 1990s, similar reasoning led to the "must carry" rule, which required cable companies to carry certain channels to communities where they were the only providers of those channels.

As I said, I need to write an essay on the broader issue.

03 Jun 11:32

Comic for June 2, 2013

31 May 13:20

El problema de parada y los castores laboriosos

by txipi

2012 fue el Alan Turing Year, año en el que se conmemora el nacimiento de Alan Turing, un matemático fundamental dentro de las ciencias de la computación.

En la Facultad de Ingeniería de la Universidad de Deusto realizamos dos acciones para celebrarlo: 1) el cambio de nombre de una de nuestras salas más «nobles» a «Sala Turing» y 2) una sesión de charlas cortas (10-15 mins) relacionadas con la figura de Alan Turing

Mi contribución fue una charla de introducción al problema de parada y a los «castores laboriosos» (tema del que ya hemos hablado por aquí) durante esa sesión de homenaje a Alan Turing.

Espero que os guste y os anime a echar un vistazo al resto de charlas cortas que se dieron ese día (muy interesantes), así como al resto de material que se generó en la Red en torno al papel fundamental de Alan Turing en el siglo XX.

PD: debería haber empezado la entrada con una disculpa por el silencio, pero creo que es muy cansino, así que considérese esta postdata como tal O;)

28 May 09:31

05.27.2013

Cyanide and Happiness, a daily webcomic

Copy this into your blog, website, etc.
<a href="http://www.explosm.net/comics/3184/"><img alt="Cyanide and Happiness, a daily webcomic" src="http://www.flashasylum.com/db/files/Comics/Kris/built.png" border=0></a><br />Cyanide & Happiness @ <a href="http://www.explosm.net">Explosm.net</a>

...or into a forum
[URL="http://www.explosm.net/comics/3184/"]
[IMG]http://www.flashasylum.com/db/files/Comics/Kris/built.png[/IMG][/URL]
Cyanide & Happiness @ [URL="http://www.explosm.net/"]Explosm.net[/URL]
<—- Share this comic!

27 May 09:40

05.26.2013

Cyanide and Happiness, a daily webcomic

Copy this into your blog, website, etc.
<a href="http://www.explosm.net/comics/3183/"><img alt="Cyanide and Happiness, a daily webcomic" src="http://www.flashasylum.com/db/files/Comics/Dave/theonlyplaneicoulddisguisemypenisasisanairbusa380andthatsahilariousquipaboutmygiganticpenisgirthnonplanetypesalsodontdisguiseyourdickasastealthbomberthathasconnoctationsthatlllandyouinprison.png" border=0></a><br />Cyanide & Happiness @ <a href="http://www.explosm.net">Explosm.net</a>

...or into a forum
[URL="http://www.explosm.net/comics/3183/"]
[IMG]http://www.flashasylum.com/db/files/Comics/Dave/theonlyplaneicoulddisguisemypenisasisanairbusa380andthatsahilariousquipaboutmygiganticpenisgirthnonplanetypesalsodontdisguiseyourdickasastealthbomberthathasconnoctationsthatlllandyouinprison.png[/IMG][/URL]
Cyanide & Happiness @ [URL="http://www.explosm.net/"]Explosm.net[/URL]
<—- Share this comic!

27 May 09:37

Cells

Now, if it selectively kills cancer cells in a petri dish, you can be sure it's at least a great breakthrough for everyone suffering from petri dish cancer.
20 May 10:43

May 17, 2013


Have I mentioned lately that we have a facebook club?
20 May 09:34

Comic for May 20, 2013

17 May 10:24

C++14 Committee Draft (CD) Published at isocpp.org—Michael Wong

[Ed.: Thanks to Michael Wong for sharing his commentary and perspective on the C++14 CD while on the scene at the C++Now conference. Posted at the IBM C/C++ Cafe blog.]

C++14 Committee Draft (CD) published at isocpp.org

C++14 Committee Draft is here and can be accessed at isocpp.org. This is in keeping with the practice of greater transparency ... [and] was also announced to the C++NOW crowd by Jens Weller at the Community evening session last night.

 

14 May 13:17

Las guitarras espaciales de Chris Hadfield

by noreply@blogger.com (Daniel Marín)
Mientras apura sus últimas horas en la estación espacial, el ya excomandante de la Expedición 35 Chris Hadfield ha vuelto a saltar a la fama por este vídeo en el que lleva a cabo una versión de la famosa Space oddity de David Bowie. No es la primera vez que alguien canta en el espacio, pero el resultado es espectacular:


Y es que Hadfield ha aprovechado su estancia en el espacio para tocar la guitarra durante su tiempo libre e incluso ha llevado a cabo algún que otro 'concierto', como esta gran interpretación de la pegadiza canción I.S.S. (Is Someone Singing) junto con Barenaked Ladies:


O la que se considera la primera grabación 'profesional' de una canción desde la ISS, Jewel in the night (sin vídeo):


Todas estas canciones estarán en un próximo álbum que aparecerá una vez regrese Hadfield a la Tierra. La guitarra de la ISS es, al igual que Hadfield, canadiense. Se trata de una guitarra acústica Larrivée Parlor fabricada en Vancouver y llegó a la estación en 2001 a bordo del transbordador espacial Discovery en la misión STS-105. El propio Hadfield visitó la fabrica el año pasado antes de su vuelo para aprender cómo sacarle el máximo provecho a la guitarra:


Hadfield con la guitarra Larrivée Parlor en la Cupola de la ISS (NASA).

Dan Burbank con la guitarra de la ISS (NASA).

Desde que la guitarra está en la estación, casi todas las tripulaciones la han tocado en mayor o menor medida como parte de los ejercicios de relajación psicológica recomendados por la NASA para los astronautas de las diferentes expediciones. Por ejemplo, aquí tenemos a Ron Garan tocando un blues con bastante menos gracia que Hadfield:


Hadfield es todo un consumado veterano en esto de las guitarras espaciales. Ya durante su primera misión espacial, la STS-74 Atlantis, el canadiense llevó en noviembre de 1995 una pequeña guitarra plegable a la estación rusa Mir, donde se sumaría a la guitarra acústica de fabricación rusa ya existente. Esta guitarra sería posteriormente traída de regreso a la Tierra en otro vuelo del transbordador.

Hadfield con la guitarra que llevó a la Mir en 1995 durante la STS-74 Atlantis (NASA).

Y es que, efectivamente, la primera guitarra en alcanzar el espacio fue rusa. Despegó el 8 de agosto de 1978 a bordo de la nave de carga Progress 3, que se acoplaría luego con la estación Salyut-6. Allí sería recibida con agrado por Vladímir Kovalionok y Aleksandr Ivanchenkov (en realidad, era la guitarra personal de Kovalionok). Kovalionok se convirtió en la primera persona en tocar la guitarra en órbita y en la primera en tocar desde el espacio para un público terrestre. La primera canción que cantó fue Lizhi u pechki stoyat (Лыжи у печки стоят).

La guitarra pronto se convirtió un una auténtica terapia para los cosmonautas durante los vuelos de larga duración. Yuri Romanenko, que permaneció 326 días en la Mir, aprendió a tocar la guitarra durante su misión e incluso compuso veinte canciones que serían publicadas en un disco con posterioridad. De hecho, la guitarra de la Mir tiene una historia a sus espaldas digna de una película. Fue lanzada originalmente hacia la estación Salyut-7, pero en mayo de 1986 los cosmonautas Leonid Kizim y Vladímir Soloviov se la llevaron en la nave Soyuz T-15 hasta la Mir, convirtiéndose así en la primera y única guitarra en estar en dos estaciones espaciales distintas. Terminaría sus días quemándose en la atmósfera cuando la Mir se destruyó en 2001. Como curiosidad, la primera guitarra norteamericana en el espacio, una pequeña CF Martin Backpacker -que era más bien un timple canario que una guitarra- voló en marzo de 1994 durante la misión STS-62 Columbia de la mano del astronauta Pierre Thuot.

Gennadi Strékalov tocando la guitarra en la Mir con la tripulación de la STS-71 (NASA).

Pierre Thuot con la primera guitarra espacial norteamericana en la STS-62 (NASA).

Lo que está claro es que Hadfield y su guitarra pasarán a la historia de la ISS como uno de los grandes momentos en la ya larga vida de esta estación. Debemos agradecer a Hadfield el que hoy mucha gente sepa que tenemos una estación espacial allá arriba. Gracias, comandante, y buen viaje de regreso a casa.
09 May 10:47

Mathematical formulas are designed to be pretty, not to be suitable for computation

by Raymond Chen - MSFT

When you ask a mathematician to come up with a formula to solve a problem, you will get something that looks pretty, but that doesn't mean that it lends itself well to computation.

For example, consider the binomial coefficient, traditionally written nCk or C(n, k), and in more modern notation as ( nk ). If you ask a mathematician for a formula for the binomial coefficient, you will get the elegant reply

( n )  =  n!
k k!(nk)!

(That took forever to format. I will use the traditional notation from now on purely for typographical expediency.)

This is a very beautiful formula, but it's horrible for actual computation because the factorials will be very expensive and are likely to overflow your integer data type even at low values of n. (So you may as well just use a lookup table.) And the k! in the denominator exactly cancels the first k factors in n!, so most of your work in multiplying the numbers together is just going to be undone by the division.

For computation, you're much better off using the recurrence C(n, k) = C(n − 1, k − 1) × nk. This is the recurrence you learned in high school when you had to calculate binomial coefficients by hand: You start with 1 · xⁿ and then to get the next coefficient, you multiply by the exponent on the x and divide by the current position (starting at 1), then decrement the exponent. For example, let's calculate the binomial coefficients C(8, k).

1  · x bring down the 8 and divide by 1 (resulting in 1 × 8 ÷ 1 = 8), then decrement the exponent
8  · x bring down the 7 and divide by 2 (resulting in 8 × 7 ÷ 2 = 28), then decrement the exponent
28  · x bring down the 6 and divide by 3 (resulting in 28 × 6 ÷ 3 = 56), then decrement the exponent
56  · x bring down the 5 and divide by 4 (resulting in 56 × 5 ÷ 4 = 70), then decrement the exponent
70  · x bring down the 4 and divide by 5 (resulting in 70 × 4 ÷ 5 = 56), then decrement the exponent
56  · x³ bring down the 3 and divide by 6 (resulting in 56 × 3 ÷ 6 = 28), then decrement the exponent
28  · x² bring down the 2 and divide by 7 (resulting in 28 × 2 ÷ 7 = 8), then decrement the exponent
8  · x¹ bring down the 1 and divide by 8 (resulting in 8 × 1 ÷ 8 = 1), then decrement the exponent
1  · x bring down the 0, which makes everything zero

(Am I the only person who calculated binomial coefficients by hand?) Notice that the calculations in the second half are the exact inverse of the calculations of the first half, so you only have to do the computations halfway, and then you can just mirror the rest. This is just another way of seeing that C(n, k) = C(n, nk).

This technique lets you evaluate C(50, 7) = 99884400 without overflowing a 32-bit integer.

Often people will ask for an efficient way of calculating factorials, when in fact they don't really need factorials (which is a good thing, because that would require a bignum package); they are really just trying to evaluate a formula that happens to be expressed mathematically with factorials (because factorials are pretty).

Another place pretty formulas prove unsuitable for computation is in Taylor series. The denominator of a Taylor series is typically a factorial, and the numerator can get quite large, too. For example, exp(x) = Σ xⁿn!. Instead of calculating the power and factorial at each term, use the recurrence

xn  =  x   xn−1
n! n (n − 1)!

In compiler-terms, you're strength-reducing the loop.

Of course, another problem is that you are adding large numbers first, and then adding smaller numbers later. From a numerical analysis point of view, you should add the smaller numbers first so that they can retain significance longer.

As an example, consider that you have to add the following numbers: 999, and ten 0.1's, and suppose your floating point format is good to only three significant digits. If you added them largest to smallest, you would get this:

999
999 + 0.1  = 999 (three sigificant digits)
999 + 0.1  = 999 (three sigificant digits)
... and so on ...

Your final total will be 999. But if you added the smaller numbers first, then you would get

0.1
0.1 + 0.1  = 0.2
0.2 + 0.1  = 0.3
... and so on ...
0.9 + 0.1  = 1
1 + 999  = 1000

By adding the small numbers first, you gave them a chance to accumulate to something meaningful before the big number came along and swamped them.

Remember, the way a formula is written on paper is not necessarily the best way of computing it. (And if the formula was written by a mathematician, it is almost certainly not!)

08 May 15:31

Como no hacer el login de una intranet

by Eidan
slack

LOL!

Captura de pantalla 2013-04-28 a la(s) 12.41.26

08 May 12:38

Rendering PCM with simulated phosphor persistence

by noreply@blogger.com (Oona Räisänen)

When PCM waveforms and similar function plots are displayed on screen, computational speed is often preferred over beauty and information content. For example, Audacity only draws the local maximum envelope amplitude and (what appears to be) RMS power when zoomed out, and when zoomed in, displays a very straightforward linear interpolation between samples.

Here's the startup beep of my Kenwood TK-2302, rendered by Audacity:

Audacity waveform

Analogue oscilloscopes, on the other hand, do things differently. An electron beam scans a phosphor screen at a constant X velocity, lighting a dot everywhere it hits. The dot brightness is proportional to the time the electron beam was directed at it. Because the X speed of the beam is constant and the Y position is modulated by the waveform, brightness gives information about the local derivative of the function.

Of course, PCM is all about "dots" as well, so we could possibly mimic this behavior digitally. I'm going to simulate an electron beam by first oversampling the above waveform by an insane amount – at 1,099,961 Hz, to be exact. (It's a prime number as well, hopefully minimizing aliasing artifacts.) Downpass filtering follows, with a cutoff frequency at the Nyquist frequency of the original PCM. Now, a program reads in the processed PCM and for each sample will make the corresponding dot on the XY plane a little brighter. (Actually each sample will affect 4 image pixels because of bilinear interpolation.) This method gives us a much more interesting rendering:

Now how cool is that? It looks like an X-ray of the signal. We can see right away that the beep is roughly a square wave, because there's light on top and bottom of the oscillation envelope but mostly darkness in between. Minute changes in the harmonic content are also visible as interesting banding and ribbons.

At very high zoom, Audacity doesn't even bother reconstructing the actual waveform but just thinks of it as a "connect the dots" puzzle. This is computationally feasible, of course. Oversampling at 3,000,017 Hz and downpass filtering at the original Nyquist frequency, on the other hand, results in an apparent reconstruction of the analogue wave:

Wave closeup

Finally, the soprano section of the Finnish Radio Chamber Choir singing a D note in a piece by Einojuhani Rautavaara:

Relevant code for scientific interest in this Gist.

Update: The bit about prime resampling rates seems to be irrelevant. It was supposed to prevent the new sample rate from coinciding with a harmonic of the waveform, and producing a "dotted" result, or Moiré pattern. Such patterns emerged nevertheless. Perhaps adding Gaussian noise would work against this.

07 May 09:59

GotW #1: Variable Initialization—or Is It?—Herb Sutter

slack

Guru of the Week columns are being updated to C++14! :D

Herb Sutter is resuming his Guru of the Week series of problem-and-solution articles about coding in C++, with the intent to gradually update the 88 existing issues and write a few more along the way.

The first problem was posted today:

GotW #1: Variable Initialization -- or Is It? (3/10)

by Herb Sutter

This first problem highlights the importance of understanding what you write. Here we have a few simple lines of code — most of which mean something different from all the others, even though the syntax varies only slightly.

The solution is coming "soon"...

02 May 14:51

Stop Drawing Dead Fish

slack

Great talk :D

People are alive -- they behave and respond. Creations within the computer can also live, behave, and respond... if they are allowed to. The message of this talk is that computer-based art tools should embrace both forms of life -- artists behaving through real-time performance, and art behaving through real-time simulation. Everything we draw should be alive by default.
30 Apr 10:56

04.29.2013

slack

GENIUS!

Cyanide and Happiness, a daily webcomic
Copy this into your blog, website, etc.
<a href="http://www.explosm.net/comics/3155/"><img alt="Cyanide and Happiness, a daily webcomic" src="http://www.flashasylum.com/db/files/Comics/Kris/beaker.png" border=0></a><br />Cyanide & Happiness @ <a href="http://www.explosm.net">Explosm.net</a>
...or into a forum
[URL="http://www.explosm.net/comics/3155/"]
[IMG]http://www.flashasylum.com/db/files/Comics/Kris/beaker.png[/IMG][/URL]
Cyanide & Happiness @ [URL="http://www.explosm.net/"]Explosm.net[/URL] <—- Share this comic!
25 Apr 10:28

Dark corners of C/C++: The typedef keyword doesn't need to be the first word on the line

by Raymond Chen - MSFT

Here are some strange but legal declarations in C/C++:

int typedef a;
short unsigned typedef b;

By convention, the typedef keyword comes at the beginning of the line, but this is not actually required by the language. The above declarations are equivalent to

typedef int a;
typedef short unsigned b;

The C language (but not C++) also permits you to say typedef without actually defining a type!

typedef enum { c }; // legal in C, not C++

In the above case, the typedef is ignored, and it's the same as just declaring the enum the plain boring way.

enum { c };

Other weird things you can do with typedef in C:

typedef;
typedef int;
typedef int short;

None of the above statements do anything, but they are technically legal in pre-C89 versions of the C language. They are just alternate manifestations of the quirk in the grammar that permits you to say typedef without actually defining a type. (In C89, this loophole was closed: Clause 6.7 Constraint 2 requires that "A declaration shall declare at least a declarator, a tag, or the members of an enumeration.")

That last example of typedef int short; is particularly misleading, since at first glance it sounds like it's redefining the short data type. But then you realize that int short and short int are equivalent, and this is just an empty declaration of the short int data type. It doesn't actually widen your shorts. If you need to widen your shorts, go see a tailor.¹

Note that just because it's legal doesn't mean it's recommended. You should probably stick to using typedef the way most people use it, unless you're looking to enter the IOCCC.

¹ The primary purpose of this article was to tell that one stupid joke. And it's not even my joke!

23 Apr 09:28

Penultimate Author

indispensable_but_eminently_replaceable
22 Apr 11:27

April 19, 2013


Due to the events in Boston, we are postponing BAHFest. If you bought a ticket, we're working on setting up a refund. Sorry, everyone. If you are in Boston, stay indoors and watch the news.

18 Apr 13:56

The $12 Gongkai Phone

by bunnie

How cheap can you make a phone?

Recently, I paid $12 at Mingtong Digital Mall for a complete phone, featuring quad-band GSM, Bluetooth, MP3 playback, and an OLED display plus keypad for the UI. Simple, but functional; nothing compared to a smartphone, but useful if you’re going out and worried about getting your primary phone wet or stolen.

Also, it would certainly find an appreciative audience in impoverished and developing nations.


$12 is the price paid for a single quantity retail, contract-free, non-promotional, unlocked phone — in a box with charger, protective silicone sleeve, and cable. In other words, the production cost of this phone is somewhere below the retail price of $12. Rumors place it below $10.

This is a really amazing price point. That’s about the price of a large Domino’s cheese pizza, or a decent glass of wine in a restaurant. Or, compared to an Arduino Uno (admittedly a little unfair, but humor me):

Spec This phone Arduino Uno
Price $12 $29
CPU speed 260 MHz, 32-bit 16 MHz, 8-bit
RAM 8MiB 2.5kiB
Interfaces USB, microSD, SIM USB
Wireless Quadband GSM, Bluetooth -
Power Li-Poly battery, includes adapter External, no adapter
Display Two-color OLED -

How is this possible? I don’t have the answers, but it’s something I’m trying to learn. A teardown yields a few hints.


First, there are no screws. The whole case snaps together.

Also, there are (almost) no connectors on the inside. Everything from the display to the battery is soldered directly to the board; for shipping and storage, you get to flip a switch to hard-disconnect the battery. And, as best as I can tell, the battery also has no secondary protection circuit.

The Bluetooth antenna is nothing more than a small length of wire, seen on the lower left below.

Still, the phone features accoutrements such as a back-lit keypad and decorative lights around the edge.

The electronics consists of just two major ICs: the Mediatek MT6250DA, and a Vanchip VC5276. Of course, with price competition like this, Western firms are suing to protect ground: Vanchip is in a bit of a legal tussle with RF Micro, and Mediatek has also been subject to a few lawsuits of its own.

The MT6250 is rumored to sell in volume for under $2. I was able to anecdotally confirm the price by buying a couple of pieces on cut-tape from a retail broker for about $2.10 each. [No, I will not broker these chips or this phone for you...]



That beats the best price I’ve ever been able to get on an ATMega of the types used in an Arduino.

Of course, you can’t just call up Mediatek and buy these; and it’s extremely difficult to engage with them “going through the front door” to do a design. Don’t even bother; they won’t return your calls.

However, if you know a bit of Chinese, and know the right websites to go to, you can download schematics, board layouts, and software utilities for something rather similar to this phone…”for free”. I could, in theory, at this point attempt to build a version of this phone for myself, with minimal cash investment. It feels like open-source, but it’s not: it’s a different kind of open ecosystem.

Introducing Gongkai

Welcome to the Galapagos of Chinese “open” source. I call it “gongkai” (公开). Gongkai is the transliteration of “open” as applied to “open source”. I feel it deserves a term of its own, as the phenomenon has grown beyond the so-called “shanzhai” (山寨) and is becoming a self-sustaining innovation ecosystem of its own.

Just as the Galapagos Islands is a unique biological ecosystem evolved in the absence of continental species, gongkai is a unique innovation ecosystem evolved with little western influence, thanks to political, language, and cultural isolation.

Of course, just as the Galapagos was seeded by hardy species that found their way to the islands, gongkai was also seeded by hardy ideas that came from the west. These ideas fell on the fertile minds of the Pearl River delta, took root, and are evolving. Significantly, gongkai isn’t a totally lawless free-for-all. It’s a network of ideas, spread peer-to-peer, with certain rules to enforce sharing and to prevent leeching. It’s very different from Western IP concepts, but I’m trying to have an open mind about it.

I’m curious to study this new gongkai ecosystem. For sure, there will be critics who adhere to the tenets of Western IP law that will summarily reject the notion of alternate systems that can nourish innovation and entrepreneurship. On the other hand, it’s these tenets that lock open hardware into technology several generations old, as we wait for patents to expire and NDAs to lift before gaining access to the latest greatest technology. After all, 20 years is an eternity in high tech.

I hope there will be a few open-minded individuals who can accept an exploration of the gongkai Galapagos. Perhaps someday we can understand — and maybe even learn from — the ecosystem that produced the miracle of the $12 gongkai phone.

17 Apr 12:31

Authorization

Before you say anything, no, I know not to leave my computer sitting out logged in to all my accounts. I have it set up so after a few minutes of inactivity it automatically switches to my brother's.
16 Apr 09:36

La evolución de acceso móvil de los lectores, y los medios online

by gallir

Estas son estadísticas de sistemas operativos en Menéame, mirad los porcentajes de cada sistema operativo:

Hace dos años:

Screenshot from 2013-04-15 15:29:51

Hace un año:

Screenshot from 2013-04-15 15:28:41

Hace seis meses:

Screenshot from 2013-04-15 15:26:52

Ahora:

Screenshot from 2013-04-15 15:32:31

El último fin de semana:

Screenshot from 2013-04-15 15:35:14

Conclusión: Android es el segundo sistema operativo, iOS es el tercero. Por encima de Mac y GNU/Linux. Android e iOS representan el 30% de las visitas. La inmensa mayoría del crecimiento se dio en los últimos dos años.

¿Cómo están los medios adaptándose a este cambio tan radical de la forma de acceder a las noticias?

Por las capturas de algunos de ellos (en un Galaxy Nexus, tomadas casi al azar, de las últimas 3 páginas de portadas de Menéame), veréis que en general muy mal. Sólo tres tenían una versión optimizada para móviles. Los demás es la misma versión web, que obliga a hacer zoom en la pantalla, a veces con pésimos resultados. Y en la mayoría la página tarda eones en cargar, especialmente por la publicidad. En otros incluso te aparece un intersticial con el botón de cerrar tan pequeño y tan en el borde, que es casi tarea imposible.

Todos nos haríamos un favor si se molesta menos al usuario, a veces basta con ocultar una columna con el CSS, y/o quitar una parte de la publicidad.

Screenshot_2013-04-15-15-16-33 Screenshot_2013-04-15-15-13-44 Screenshot_2013-04-15-15-12-58 Screenshot_2013-04-15-15-09-45 Screenshot_2013-04-15-15-08-51 Screenshot_2013-04-15-15-08-27 Screenshot_2013-04-15-15-08-05 Screenshot_2013-04-15-15-07-48 Screenshot_2013-04-15-15-06-48 Screenshot_2013-04-15-15-06-14 Screenshot_2013-04-15-15-05-36 Screenshot_2013-04-15-15-04-47
16 Apr 09:17

If I Made Another Monkey Island...

Yeah, I know, that sounds like the title of the O.J. Simpson book. I realized that after I typed it, but I'm not going to change it.

So, before I get into this fanciful post, I want to make one thing perfectly clear... actually, I'm just going to make it my first point.  It's probably the most important one.  Actually, I'll make it the first two points.

One - I am not making another Monkey Island. I have no plans to make another Monkey Island. I am not formulating plans to make another Monkey Island.

Two - Let me say that again.  There is no new Monkey Island in works and I have no plans to make one.  I'm just thinking and dreaming and inviting you come along with me.  Please your keep your hands inside the boat at all times.  No standing or you might get wet.

But, If I made another Monkey Island...

Three - It would be a retro game that harkened back to Monkey Island 1 and 2.  I'd do it as "enhanced low-res".  Nice crisp retro art, but augmented by the hardware we have today: parallaxing, depth of field, warm glows, etc.  All the stuff we wanted to do back in 1990 but couldn't.  Monkey Island deserves that.  It's authentic.  It doesn't need 3D.  Yes, I've seen the video, it's very cool, but Monkey Island wants to be what it is.  I would want the game to be how we all remember Monkey Island.

Four - It would be a hardcore adventure game driven by what made that era so great. No tutorials or hint systems or pansy-assed puzzles or catering to the mass-market or modernizing.  It would be an adventure game for the hardcore.  You're going to get stuck.  You're going to be frustrated.  Some puzzles will be hard, but all the puzzles will be fair.  It's one aspect of Monkey Island I am very proud of.  Read this.

Five - I would lose the verbs.  I love the verbs, I really do, and they would be hard to lose, but they are cruft.  It's not as scary as it sounds.  I haven't fully worked it out (not that I am working it out, but if I was working it out, which I'm not, I wouldn't have it fully worked out).  I might change my mind, but probably not.  Mmmmm... verbs.

Six - Full-on inventory.  Nice big juicy icons full of pixels.  The first version of Monkey Island 1 had text for inventory, a later release and Monkey Island 2 had huge inventory icons and it was nirvana.  They will be so nice you'll want to lick them. That's a bullet-point for the box.

Seven - There would be a box. I imagine most copies would be sold digitally, but sometimes you just want to roll around in all your adventure game boxes. I know I do.  Besides, where would you store the code wheel?

Eight - There would be dialog puzzles.  They weren't really puzzles, but that's what we called them.  Being able to tell four jokes at once and meander and getting lost in the humor of a conversation is the staple of Monkey Island.  No one has done it better since.  Just my opinion.

Nine - I would rebuild SCUMM.  Not SCUMM as in the exact same language, but what SCUMM brought to those games. It was a language built around making adventure games and rapid iteration.  It did things Lua could never dream of.  When Lua was in High School, SCUMM beat it up for lunch money.  True story.  SCUMM lived and breathed adventure games.  I'd build an engine and a language where funny ideas can be laughed about at lunch and be in the game that afternoon.  SCUMM did that. It's something that is getting lost today.

Ten - It would be made with a very small team.  Not 30 or 20, but 10 or less.  It means the game would take longer, but it would be more personal and crafted with love. Monkey love. Wait... that's not what I meant...

Eleven - The only way I would or could make another Monkey Island is if I owned the IP.  I've spent too much of my life creating and making things other people own.  Not only would I allow you to make Monkey Island fan games, but I would encourage it.  Label them as such, respect the world and the characters and don't claim they are canon.  Of course, once the lawyers get ahold of that last sentence it will be seven pages long.

Twelve - It would be called Monkey Island 3a.  All the games after Monkey Island 2 don't exist in my Monkey Island universe. My apologies to the all talented people who worked on them and the people who loved them, but I'd want to pick up where I left off.  Free of baggage.  In a carnival.  That doesn't mean I won't steal some good ideas or characters from other games. I'm not above that.

Thirteen - It won't be the Monkey Island 3 I was going to make in 1992. I'm not the same person I was back then. I could never make that game now.  It is lost to time.  Hopefully this one would be better.

Fourteen - The press won't get advanced copies.  I know all the reasons they want to get a game in advance, and they are all valid, but I feel they should play it at the same time you do.  I hope they won't be mad at me.  My Metacritic score hopes they won't be mad it me.

Fifteen - It would have full voice.  It's something we dreamed of back then and we can do it now.

Sixteen - If I used Kickstarter, there would be no fancy videos of me trying to look charming (as if I could).  No concept art or lofty promises or crazy stretch goals or ridiculous reward tiers.  It would be raw and honest.  It would be free of hype and distractions that keep me from making the best game I could.  True, I wouldn't raise huge sums of money or break any records, but that's not what I want to do. I want to make a game.

Seventeen - The game would be the game I wanted to make.  I don't want the pressure of trying to make the game you want me to make.  I would vanish for long periods of time. I would not constantly keep you up-to-date or be feeding the hype-machine.  I'd show stuff that excited me or amused me.  If you let me do those things, you will love the game. That, I promise.

I hope you've had as much fun reading this as I had writing it.

03 Apr 12:39

The if(0) trick in switch() {}

by Andreas Öman

Sometimes you have two case -statements in a switch()-section which does almost identical stuff except some initial thing. Now, here’s a neat trick (related to Duff’s device) for doing that all inline.

int v;
switch(x) {
case 1:
  v = foo();
  if(0)
case 2:
    v = bar();
  do_stuff(v);
  break;
}

You’re welcome!

22 Mar 13:40

Buñuelos de calabaza y chocolate a la taza. Receta de la madre de mi amigo César

by Esther

Hoy os traigo la receta más especial que he publicado en el blog hasta el día de hoy, y es que esta gran receta es de Carmina, la mamá de mi amigo César (Carcaixent,Valencia). Como bien sabéis me encantan todos los dulces típicos que tenemos en nuestro país, muchos de ellos me gustan tantísimo que hasta soy partidaria de que se hagan durante todo el año icon wink Buñuelos de calabaza y chocolate a la taza. Receta de la madre de mi amigo César Aun así, intento no hacerlo para no terminar pesando 200 kilos y además así hacer que esa época en la que se elaboran sea más especial comerlos.

Esta receta de buñuelos de calabaza es la mejor que he probado nunca, y creedme, he comido tantos como he hecho en mi trayectoria como pastelera. Siempre he pensado que las mejores recetas de este mundo son las de las mamás y abuelas ya que llevan cocinando toda la vida para alimentar a su familia, y hasta día de hoy no me he equivocado. Es por eso que esta receta es tan magnífica, porque Carmina la lleva haciendo muchos años para su familia y yo he tenido el honor hace un par de años de comerlos en Fallas en su casa junto a un buen chocolate a la taza.

Desde aquí agradezco de todo corazón a Carmina por haber compartido esta receta conmigo y dejar que la ponga en el blog icon smile Buñuelos de calabaza y chocolate a la taza. Receta de la madre de mi amigo César

buñuelos de calabaza 01 Buñuelos de calabaza y chocolate a la taza. Receta de la madre de mi amigo César

Como ahora mismo en casa solo somos dos, esta receta es para unos 8-10 buñuelos, si queréis que os salgan más, solo tenéis que hacer el doble o el triple de la cantidad que os pongo aquí abajo.

buñuelos de calabaza 052 Buñuelos de calabaza y chocolate a la taza. Receta de la madre de mi amigo César

Así de ricos y jugosos quedan por dentro estos buñuelos de calabaza.


Receta buñuelos de calabaza (para 8 – 10 unidades)

250 calabaza hervida

125 harina de repostería

caldo de calabaza (a ojo)

5 gr de levadura fresca

Elaboración

Lo primero que tenemos que hacer es hervir la calabaza cortada en trozos hasta que esté blanda. Cuando esté lista la sacamos, pasamos por agua fría y retiramos la piel (no tiramos el caldo de la calabaza). Una vez tengamos la calabaza en un bol la trituramos con un tenedor para que quede bien manejable. Agregamos un poco de harina, un poco de caldo y desmenuzamos la levadura fresca, mezclamos todo muy bien. Cuando todo esté bien unido agregamos el resto de la harina y vamos agregando caldo de calabaza poco a poco hasta que quede una masa ni muy líquida ni muy consistente, un término medio, y un pelín pegajosa. Tapamos con film transparente y dejamos que doble su volumen.

Yo los frío en aceite de girasol para que la calabaza siga siendo el sabor principal y no el del aceite de oliva.

Ponemos a calentar el aceite en una sartén a fuego medio y con las manos mojadas en agua coger un poco de masa haciéndole un agujero en medio antes de echarlo en la sartén. Cada vez que cojamos un buñuelo tenemos que tener las manos mojadas de agua ¡Que no se os olvide! icon smile Buñuelos de calabaza y chocolate a la taza. Receta de la madre de mi amigo César

buñuelos de calabaza 03 Buñuelos de calabaza y chocolate a la taza. Receta de la madre de mi amigo César

Vamos moviendo los buñuelos de calabaza por la sartén con la ayuda de una pala de madera o espumadera y cuando se hayan hinchado y lleven un rato en el aceite les damos la vuelta para que se hagan por el otro lado. En esta foto de abajo podéis ver que el de la derecha del todo está recién dado la vuelta.

buñuelos de calabaza 04 Buñuelos de calabaza y chocolate a la taza. Receta de la madre de mi amigo César

Una vez lo sacamos del aceite lo dejamos escurrir en papel de cocina unos segundos y lo pasamos por azúcar o azúcar y canela ¡eso ya a gustos!

buñuelos de calabaza 05 Buñuelos de calabaza y chocolate a la taza. Receta de la madre de mi amigo César

Aquí veis el interior del buñuelo lo jugoso que queda por la cantidad de calabaza que lleva la receta, además su sabor es increíble porque aprovechando el caldo donde la hemos hervido potencia muchísimo más su sabor.

Y como no podía faltar para acompañar estos ricos buñuelos ¡Una buena taza de chocolate!

buñuelos de calabaza 06 Buñuelos de calabaza y chocolate a la taza. Receta de la madre de mi amigo César

A mi me gustan los chocolates a la taza espesos pero odio cuando lo pido en algún sitio y sabe demasiado a fécula… Es por eso que desde hace muchísimo tiempo, mi chocolate a la taza no lleva espesante y como podéis apreciar en la foto queda con una textura espesa y deliciosa gracias a la nata.

Receta chocolate a la taza espeso

Para mi chocolate a la taza para 2 personas, medir con las mismas tazas donde se va a servir.

3/4 de la taza de nata 21%

1/4 de la taza de leche

1 cucharada sopera de azúcar por persona.

1 cucharada sopera de cacao en polvo de buena calidad por persona también. (En el supermercado podéis encontrar cacao de la marca Valor)

1 chupito de coñac

Poner a fuego medio alto y mover con las varillas fuerte, cuando chapotee la primera vez retirar del fuego y agregar un chupito de coñac. Remover bien con las varillas y poner en el fuego de nuevo hasta el segundo hervor que ya estará espeso.

Si no os gustan los grumos de cacao (a mí me encantan) y quedan algunos, pasar la batidora. A este chocolate a la taza se le puede poner nata por encima si queréis, si no os gusta el alcohol no le pongáis el chupito, yo hay veces que que también le he echado un pelín de canela y queda delicioso.

¡Que disfrutéis de esta receta!

22 Mar 11:55

03/20/13 PHD comic: 'How irreplaceable are you?'

Piled Higher & Deeper by Jorge Cham www.phdcomics.com
Click on the title below to read the comic
title: "How irreplaceable are you?" - originally published 3/20/2013

For the latest news in PHD Comics, CLICK HERE!