Monday 14 November 2011

C# vs C++ syntax, round 1

While I was trying to learn F#, I logged on my project euler account to start with simple algorithms to practice. But when I looked the first problem, which I've solved a couple of years ago in C++, I couldn't help myself stopping putting my hands on the code editor and solving it in C# using Linq

The description of the problem:

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.


The solution in C++ is something like

int problem_01( )
{
int sum = 0;
for (int i = 0; i < 1000; ++i)
{
if ((i % 3) == 0 || (i % 5) == 0)
sum += i;
}

return sum;
}

... and the equivalent in C#


public static int Prob01()
{
  return 
    Enumerable.Range(1, 999).Where(x => (x % 3) == 0 || (x % 5) == 0).Sum();
}

For me it's clear which one is more concise and better express what I'm doing.

Before I forget it, the equivalent in F# can be implemented like that:

let result = List.sum(List.filter(fun x -> x%3=0 || x%5 =0)[1..999])



Friday 11 November 2011

I walk beside you

O título deste post (Eu caminho ao seu lado) poderia muito bem ter sido extraído de um texto da bíblia ou mesmo de uma música cristã. Mas não foi o caso. No momento que escrevo estou no trabalho ouvindo pela primeira vez (apesar de ser antigo) o álbum Octavarium do Dream Theater. Devido a questões pessoais estou sentindo meu coração dilacerado, o que por certo lado tem me fortalecido na fé visto que não tenho nada a quem me apegar e que possa me resgatar a não ser o Sr. Jesus.

Quando James Labrie começou cantar este som, comecei a prestar atenção na letra, e olha, fiquei extremamente surpreso. Era como Jesus falando comigo - o que pode soar como uma heresia para muitos mas não me importa meu relacionamento com Deus é entre eu e Ele além do que não sou (mais) adepto da teologia que o diabo está em tudo que não é 'cristão'.

Corri na internet para ver a letra, e realmente não havia entendido mau. Incrível como a letra de uma banda 'secular' consegue ser mais profunda que a de muitas bandas de música gospel que se limitam a repetir os mesmos chavões evangélicos. Claro que não se pode dizer que o personagem que faz a narrativa é Jesus, mas mais importante que isso é que boa parte da letra desta música reflete um pouco do que Jesus é em nossas vidas como grande amigo e intercessor.

Fica ai a letra traduzida para o Português - tradução livre feita por mim com ajuda do google e cambridge dictionary. Em seguida o vídeo caso queira conhecer a música.

Eu caminho ao seu lado

Há uma história em seus olhos
Eu posso ver a dor por trás do seu sorriso
Para cada sinal que eu reconheço
Outro me escapa

Deixe-me saber o que atormenta sua mente
Deixe-me ser aquele que melhor te conhece
Ser aquele que te sustenta
Quando você sente que está afundando

Diga-me, mais uma vez
O que está debaixo da dor que você está se sentindo
Não me abandone
Ou pense que você não pode ser salvo

Chorus
Eu caminho ao seu lado
Onde quer que esteja
Para o que for preciso
Não importa o quão longe

Para tudo que há de vir
E para tudo há de ir
Eu caminho ao seu lado
Eu caminho ao seu lado

Desabafe para mim os seus fantasmas
Descanse seus pensamentos cansados sobre as minhas mãos
Entre no local sagrado
Quando todos os seus sonhos parecem destruídos

Ressoe no interior deste templo
Deixe-me ser aquele que te melhor entende
Ser o que te carrega
Quando você não puder mais andar

Diga-me, mais uma vez
O que tem debaixo dessa superfície sangrenta
Se você perdeu o seu caminho
Vou levá-lo de volta para ele

Chorus

Oh, quando tudo está errado
Oh, quando a desesperança te rodeia
Oh o sol nascerá novamente
A maré que você nada contra te levará de volta para casa
Então, não desista
Não se entregue

Chorus

...





Em tempo, vasculhando na web encontrei esse comentário em um site que discute a letra de músicas, achei interessante e vou reproduzi-lo aqui:

It's a song about "Walking with God"; in chronological order:

"I can see the hurt behind your smile"- it's similar to Psalm 139:16-"You know me inside out..."

"Let me know what plagues you mind"- it's similar to Psalm 139:23- "Search me,O God, and know my heart;...my anxious thoughts".

Then,"What's beneath the pain you feeling", Psalm 69:29-"I am in pain and distress...O God protect me";

Then,"Don't abandon me", Deut.31:6-"He will never leave you nor forsake you".

Then,the Chorus-"I walk beside you", I Peter 5:7-"Cast all your anxiety on him because he cares for you",

Then, "Through all that may come and all That may go", Heb.13:8 - "Jesus Christ is the same yesterday, today and for ever".

Then, "Rest your tired thoughts upon my hand", Mat.11:28 - "Come to me, all you who are weary and burdened, and I will give you rest.",

Then,"Tell me once again...", Psalm 141:1-"O Lord, I call to you;come quickly to me.Hear my voice when I call to you.",

Then,"When hopelessness surrounds you... Don't give up,don't give in,Psalm 31:24-"Be strong and take heart, all you hope in the Lord".


It can be played on a Christian Radio Station... 

Friday 4 November 2011

Ele tomou sobre si as nossas enfermidades

Engraçado como esse texto é usado invariavelmente pelos crentes super-heróis, aqueles que não ficam doentes sabe (qual será o elixir (ou garrafada kkkk) que eles tomaram). Quantas vezes você já ouviu um destes crentes lhe dizer que vai orar pra sua dor de cabeça passar, ou que você está doente porque não ora, está em pecado ou porque não busca a Deus e todo aquele bla bla bla pra lá de neo-pentecostal (do qual estou farto).

Engraçado que se lermos essa profecia feita em Isaías 53 - e citada em Mateus 8:17 - veremos logo no próximo versículo o seguinte:


Mas ele foi transpassado por causa das nossas transgressões, foi esmagado por causa de nossas iniquidades; o castigo que nos trouxe paz estava sobre ele, e pelas suas feridas fomos curados. 
Isaías 53:5


Não é que eu duvide que Cristo cura até hoje, claro que ele pode curar, lembre também que estamos em um corpo perecível pois nascemos no pecado. Mas deixando isso de lado um pouco eu pergunta, não seriam essas enfermidades citadas em tais versículos doenças da alma também?

E ai eu faço mais uma perguntinha também: Se Jesus levou sobre si todas as nossas enfermidades (físicas e da alma) não deveríamos ficar doentes na nossa carne e muito menos na alma! Lógico não é?

Então por que vocês ficam dizendo que quando ficamos doentes estamos com pouca fé enquanto vocês ao invés de se aperfeiçoarem em Cristo ficam com essa de quebra de maldições, confessando pecado em público, quebrando maldição hereditária, ué Jesus não levou sobre si nossas enfermidades, ou não é bem assim, ou o que ele fez não foi suficiente?

Uma coisa tenho experimentado nesses últimos tempos, que o Sr. Jesus pode curar sim as enfermidades de nossa alma, curar o nosso interior, mas isso eu tenho feito direto com ele, sem intermediário, pode doer mais mas é mais eficaz e nos faz fortes!

Sunday 30 October 2011

Vivendo na Matrix gospel

Outro dia desses estava eu conversando com minha esposa sobre o comportamento de alguns cristãos que tem agido como loucos atrás da “benção de Deus”, e como tem sido enganados por essas igrejas que levantam impérios às custas dessa gente desesperada e desequilibrada.

Enquanto eu pensava sobre isso me veio à memória o filme Matrix – o primeiro da série. Mais especificamente a cena em que Morpheus encontra-se com Neo pela primeira vez. Nela Morpheus conta à Neo que toda a sua vida até aquele momento era uma ilusão e que enquanto ele vivia neste mundo de ilusões a energia vital do seu corpo estava sendo continuamente “sugada”, utilizada como uma bateria para alimentar as máquinas que tomavam conta da Matrix. Ele então oferece a Neo a opção de saber toda a verdade ou continuar vivendo na ilusão: “Você toma a pílula azul – a história termina aqui, você acordará em sua cama e acreditará naquilo que quiser acreditar. Você toma a pílula vermelha – você fica no país das maravilhas e eu lhe mostrarei o quão fundo o buraco do coelho chega”.

Existem muitos, mas muitos “crentes” vivendo como em uma Matrix; num mundo de ilusões onde denominações e pessoas que se auto intitulam apóstolos, bispos e pastores têm sugado quase tudo delas. Estão tão imersas em um mundo de “conquistas” (na grande maioria materiais) bençãos, restituição, tão desesperadas estão que simplesmente ficaram cegas, sem a mínima capacidade de julgamento, raciocínio e crítica; sem o mínimo discernimento das escrituras. São manipuladas por esses falsos profetas que além de sugarem suas finanças com a venda de toda sorte de amuletos gospel (toalhinhas, meia ungida, óleo, carnes e um mundo sem fim de amuletos onde a criatividade parace não ter limite), tem também sugado sua sanidade mental; e não estou falando no sentido figurativo, essas igrejas estão deixando as pessoas mentalmente doentes. Conheço pessoas que estão vivendo na “Matrix” e quando converso com elas vejo o quanto estão mentalmente doentes, quase à beira da loucura.

Pior ainda é quando tentamos argumentar com elas, na tentativa de que aceitem a “pílula vermelha”, mas elas não querem, preferem viver em suas ilusões, como diz em 2 Tessalonicenses 2:10-12:

Ele fará uso de todas as formas de engano da injustiça para os que estão perecendo, porquanto rejeitaram o amor à verdade que os poderia salvar. Por essa razão Deus lhes envia um poder sedutor, a fim de que creiam na mentira, e sejam condenados todos os que não creram na verdade, mas tiveram prazer na injustiça.

No filme, Neo escolhe conhecer a verdade, tomando a pílula vermelha. Mas ao contrário do filme, a verdade (a verdadeira doutrina) não se revela como um mundo de distopia; pelo contrário. Há um livro que há meses não tem saído da minha mente, Eclesiates. Acho que não tem na bíblia nenhum livro que escancara a realidade nua e crua da vida como Eclesiastes.

A vida com Deus não é sinônimo de uma vida sem problemas, sem doenças, sem dor, pranto. Mas muitas igrejas e pessoas têm dito que quando temos problemas é porque estamos em pecado. Então Paulo estava em pecado quando escreveu a maior parte do novo testamento e foi duramente perseguido, apanhou, foi preso e passou por náufragos. Elias estava em pecado quando deprimido desejou a morte deitado debaixo de uma árvore antes de se esconder em uma caverna. Por mais que seja difícil passar por momentos difíceis na vida, devemos crer que Deus é soberano e assim como permitiu que satanás tocasse em Jó para prová-lo e, como diz no texto abaixo de 2 Coríntios, permitiu que um mensageiro de satanás esbofeteasse Paulo para que não se exalta-se, devemos crer no que está escrito em Romanos 8:28 que “Todas as coisas cooperam para o bem daqueles que amam a Deus” TODAS!

E, para que não me exaltasse pela excelência das revelações, foi-me dado um espinho na carne, a saber, um mensageiro de Satanás para me esbofetear, a fim de não me exaltar.
Acerca do qual três vezes orei ao Senhor para que se desviasse de mim.
E disse-me: A minha graça te basta, porque o meu poder se aperfeiçoa na fraqueza. De boa vontade, pois, me gloriarei nas minhas fraquezas, para que em mim habite o poder de Cristo.
Por isso sinto prazer nas fraquezas, nas injúrias, nas necessidades, nas perseguições, nas angústias por amor de Cristo. Porque quando estou fraco então sou forte.


Ainda em Romanos Paulo diz:

E não somente isto, mas também nos gloriamos nas tribulações; sabendo que a tribulação produz a paciência,
E a paciência a experiência, e a experiência a esperança.
E a esperança não traz confusão, porquanto o amor de Deus está derramado em nossos corações pelo Espírito Santo que nos foi dado.


Agora pergunto, até quando você vai viver nessa vida de ilusões promovida pelo show gospel de rituais, sacrifícios, palavras proféticas, amuletos, objetos ungidos e mentira? 

Thursday 22 September 2011

Deus meu, Deus meu, por que me desamparaste?

Estava eu navegando na internet quando encontrei esse artigo falando sobre a saudade, o qual reflete bem o momento que estou passando agora. Mas além da dor da saudade, quando tenho orado a Deus tenho as vezes a impressão de que estou sózinho, que nem Ele tem me ouvido, como se tivesse me abandonado.

Mas me senti de certa forma consolado quando lendo este texto, me lembrei que o senhor Jesus passou por um momento semelhante, desamparado e só. O livro de Mateus no capítulo 27 retrata bem esse momento, quando Jesus está sendo crucificado.

Do versículo 39 ao 46 de Mateus 27 podemos ler:

39 E os que iam passando blasfemavam dele, meneando a cabeça

40 e dizendo: Tu, que destróis o santuário e em três dias o reedificas, salva-te a ti mesmo; se és Filho de Deus, desce da cruz.

41 De igual modo também os principais sacerdotes, com os escribas e anciãos, escarnecendo, diziam:

42 A outros salvou; a si mesmo não pode salvar. Rei de Israel é ele; desça agora da cruz, e creremos nele;

43 confiou em Deus, livre-o ele agora, se lhe quer bem; porque disse: Sou Filho de Deus.

44 O mesmo lhe lançaram em rosto também os salteadores que com ele foram crucificados.

45 E, desde a hora sexta, houve trevas sobre toda a terra, até a hora nona.

46 Cerca da hora nona, bradou Jesus em alta voz, dizendo: Eli, Eli, lamá sabactani; isto é, Deus meu, Deus meu, por que me desamparaste?

E torna a clamar no versículo 50:

50 De novo bradou Jesus com grande voz, e entregou o espírito

Fico imaginando a dor do senhor Jesus neste momento.

Mas o texto reflete um sentimento que acredito que todo cristão um dia experimentou, ou um dia experimentará. E nesse momento, quando tudo ao redor parecer não ter solução, virão os escarnecedores – dos quais alguns cristãos, “irmãos em Cristo”, dirão: você deve estar em pecado; ore mais (como se já não estivesse).

Lendo o texto de Mateus, eu me pergunto: se até mesmo Jesus, o verbo que se fez carne, parte da trindade, filho de Deus, conhecedor de toda glória e poder do reino, se até ele sentiu e teve este momento de abandono, por que eu, um pecador não posso passar pela mesma situação?

A verdade é que no fundo temos que continuar com nossa fé, por menor e mais abalada que ela esteja, e não desanimar em oração e busca, pois como diz o profeta Isaias no capítulo 59 versículo 1: 

“Eis que a mão do Senhor não está encolhida, para que não possa salvar; nem surdo o seu ouvido, para que não possa ouvir;”

Temos que continuar clamando, e lembrar que mesmo o senhor Jesus, passando por este momento de solidão, ao terceiro dia ressucitou, foi recebido aos céus a assentou-se à direita de Deus.

Deus não esqueceu ou abandonou o senhor Jesus, e o mesmo não fará conosco. Que esse momento de aparente distância de Deus, ou até mesmo dúvida quanto à sua existência, possa gerar em nós ainda mais forças para buscá-lo mais e mais. 

Sunday 10 April 2011

My first melodic minor lick


Continuing with my battle to unveil the secrets behind the altered scale, I came up with the lick of this post.

I was trying to develop new ideas in a mix of notes that came to my mind with the geometry of the scale. Then this lick started to get shape, but wasn't sounding dominant but minor though.

I then remembered that the altered scale has exactly the same of the melodic minor scale half tone upper. In my case, I was practicing over the notes of G altered, which has the same notes of Ab melodic minor. I shifted all the notes half tone up, just to make it over the key of minor A, instead of the odd key of minor Ab.

The result can be seem in the picture below. However as I'm very bad in transcribing the notes to the score - specially the time intervals - I put an audio sample in this post, just to make sure I'm expressing myself more clearly and I'll not forget the lick later.


One interesting aspect of this lick is regarding the time division. Instead of starting playing in the first sixteenth  note straight away, there's a small pause in the begging. So instead of something like counting the four time intervals per whole time (like 1, 2, 3, 4), I started it from the second or third (like 2, 3, 4, 1, where the 1 is in the first interval of the next bar if I can say that). Ok this is a bit confusing, even for me, there are some nomenclature I don´t remember and on the top that it my English is not good enough to express what I want now. Hopefully the audio will speak for itself.

Melodic minor lick - audio
The audio quality is not good, but can give you an idea. 

Sunday 3 April 2011

Pointers part II, learning how to do addition and subtraction again :-(



Last time I wrote about pointers I think the real use for then wasn't clear. I think now it can start to make more sense.

But before get to point I want, more theory makes necessary :( !

Pointer arithmetic

With normal numeric variables the result of simple operations like addition or subtraction are quite predictable if we know the contents of such variables. However this rule doesn't apply for pointers.

Pointers don't store numbers, but memory addresses. So if a pointer points to the mem. address 0x98456732 what happens if we add 1? The answer is, it depends! It depends on the pointer's type and how many bytes does that type needs to represent its information in the memory.

For example, on my 64 bits laptop using Visual Studio, a int variable has a size of 4 bytes, a double, 8 bytes while a char only 1 byte.

So when summing or subtracting pointers, this must be taken into account. Lets have a look in one example:


#include "stdafx.h"
#include <iostream>

int _tmain(int argc, _TCHAR* argv[])
{
1 int x = 10;
2 int *ptr = &x;
3
4 int address = (int)ptr;
5 printf("\nThe pointer points to %X == %X\n", ptr, address);
6
7 ptr++;
8
9 int difference = ((int)ptr) - address;
10
11 printf("%d bytes were added to %X\n", difference, address);
}


In this program at line 1 an int variable is declared and initialized with 10. In the line 2 I declared the pointer and initialized it with the address of x. Then at line 4 the address of x is assigned as a normal integer to the variable address. The printf at line 5 shows that the value stored in ptr and address are the same. Finally at line 7 the pointer is incremented by 1 unit! So now what's the value of the pointer? The answer is: the new value is equal to the original memory address plus 4! What lines 9 and 11 do is just proving what I'm saying. But why 4?

Let's call the memory address number being pointed by ptr as addr_number. The new address number obtained after the addition can be thought as:

addr_number + 1* sizeof(int) == addr_number + 1*4 == addr_number + 4
So for every arithmetic operation with pointers, we have to consider the size of the type which the pointer was declared. The same applies for subtraction. About multiplication and division, I've never seen or used it in practice but I guess the same logic applies.

Sunday 20 March 2011

Lick over dominant 7(9♭)


The last couple of days I have been trying to practice over the II - V - I cadence of chords, training both chord and scales. There is one particular scale that I really wish I could master. I find particularly challenging to apply such a scale. I'm talking about the altered scale.

It is a very rich scale in terms of sonority but when I play it note by note it sounds really odd to my ears - maybe that's why I personally find it difficult to use. This scale is mainly used over the dominant chord, and sounds very jazzy. I like to play metal solos but I'm stuffed to listen to pentatonic scales, for years I've been trying to add a little bit of fusion to my metal solos, I think it adds much more colour and tension to the sonority.

The altered scale is composed by the intervals: 1 - 2♭ - 2# - 3 - 5♭ - 5# - 7m. In some texts the 2# (which is the 9#) is written as 3♭. Although they refer to the same note, I prefer to emphasize its augmented ninth nature over a minor third. All the notes of the altered scale truly reflect some of the possible combinations a dominant chord can has:

V7(9♭) - V7(5#) - V5# ...

I've written two licks over the chords G7(9♭) and C7M. When I wrote the first one I was thinking in the very close relationship that the V7(9♭) chords have with diminished chords. If you play 7(9♭) chords every whole and a half tone you will notice that the sound you get is very similar to the one produced by a sequence of diminished chord - example:

G7(9♭) - E7(9♭) - C#7(9♭)
Fº         -    Dº      -     Bº

... and as diminish chords (include here 7(9♭) chords) are symmetric, you can substitute one by another.

So coming back to the topic, the first lick starts with the notes of the diminished scale (ascendlinging) and come back descending in the scale using the notes of the C#7M arpeggio (or the notes of Fm7 if you wish) - and yes the I#7M chord can prepare the I7M.



Play this sequence over the chords G7(9♭) - C7M


The second lick is totally constructed over the altered G scale. The last note is the major 7 note of C.



The same sequence of chords can be used here. Additionally the C#7M chord can be used like a passing chord before C7M.

Wednesday 9 March 2011

II - V - I - Part one of many


This is probably the most famous sequence of chords in contemporary western music. It can appear simple and ordinary but when we start using this sequence to prepare all the chords in the (or minor) scale chord progression (borrowed chords) things start to get interesting.

But today I want to share a experience I had this afternoon whilst practicing this sequence of chords II - V - I in the scale of C major - one drawback here is that as my second post about music I'm jumping from intervals to a more ??? I wouldn't say complex but a little bit advanced example. But soon I will write about chord progression etc. 

Back to the topic I was looking some chords that can be used in this sequence and I was amazed to notice how similar they are.

One of the sequences I was trying is composed by: IIm6 - V7(5#)- I7M.

What I want to point out is how similar the chords IIm6 and V7(5#) are . Let's have a look.
Dm6
G7(5#)
C7M
In this sequence Dm6 has the role as subdominant, G7(5#) is the dominant whilst C7M is the tonic.

Let's look others coincidences now. If we look the chord Bm7(5b):

Bm7(5b)
If we compare it with Dm6 we have exactly the same chord (unfortunately the m6 chord I chose for this example omits the 5th note A in which case would make both chords exactly the same). So we can exchange one by another - and bear in mind that this doesn't apply only for this example.

Now lets look the Dm6 chord I chose. If we compare it with a normal G7 we have almost the same chord!
G7
This is really what fascinates me about music, everything seems to be connected.

Other interesting observation can be done if we take the Dm6 chord used here and change F in the 3th string by G# we get Do. As any diminished chord is symmetric every 1 tone and a half, walking to the next symmetric position ascendingly we have Fo. Hummm, so we can play F7M - F- Dm6 and finally C7M. In this case, if I'm not wrong, Fand Dm6 are doing the same job as subdominant chords as II degree.

I think I'll stop for now, but before, one more sequence I had practiced today - using the chord shapes used here - not all:

Dm6 - G7(5#) - Bm6(5b) - C9

Sunday 27 February 2011

Intervals


New blog, fresh new posts and this is my first about music. I was looking some old stuff I wrote when I was on my early 20s – at that time I was really engaged with my music studies – and I think in this first post it would be good to write about one of the most fundamental elements in music : Intervals.

As the only instrument I play is the electric / acoustic guitar, I will have the tendency to use this instrument for some examples, but I believe this post can be used by any kind of instrument.

When we are talking about intervals we are always considering two notes. When we play one note (any) followed by a second note, we get a characteristic sound. This sound results from the difference between these two notes. That difference can be measured. Like we can measure distance in meters or feet, in music the measurement unit is called Interval.

The minimum distance between two notes is half a tone. In the guitar half tone is represented by one fret. Two frets are equivalent to one whole tone. So if we take the note C, play it followed by E, for instance, what we get is a ascending distance of two whole tones and a descending distance of four tones.

However the intervals are not named as “2 and a half tone interval”, “three whole tone interval” and so on. More important than know “how far” is one note from the other is to know how does it sound!
Lets talk about sensation, feeling. If we play the notes C followed by E we have a characteristic sound. If we play D followed by F#, we get the same interval and the same sound, I mean, the same feeling, the only difference is that it will have a slightly higher register.

Let’s give name to our intervals now. Every Interval (forget the distance and keep in mind the sound they produce) has a “name” and that name represents a typical sound, independently of the key we are playing. To know the interval we will always use the first note as the reference. Also the first note is considered to “calculate” the interval. Once again taking as example the notes C and E, the interval they produce is major third – if we start counting whole tones from C to E we get: C – D – E, three notes.

The interval between D and F#: D –E – F#: 3 notes, major third. Now the interval between E and G we get: From E to F# one whole tone but from F# to G half tone. In this case we still have an interval of third, but minor third. Between the notes G and A we have on tone, this characterizes the interval of major second.

There’s a table that can help memorizing then. But again one very important thing about intervals, is the sound of each one. We can find “relaxing intervals” like Perfect fifth, Perfect fourth (try to play the sequence C – G (5th) – C – F (4th) – C – E (3th). Sad intervals like Minor sixth: try the sequence C – G# (minor 6th) – C – G (5th). And also more tense intervals like Augmented Fourth (C – F#).


Before finish I just want to point out that this material doesn't follow music theory in all of its formalities. It also may be a bit imprecise in some definitions, so consider it just as a start point.

Sunday 20 February 2011

Pointers, it was once...

In these last 10 years working as a developer or teaching in a Introduction to Programming discipline, I've found many people struggling to understand pointers properly. Many found it a very abstract subject but the truth is it is not all that difficult to grasp.

I'll try to remember as many doubts I had listened to in order to try to write about then clearly.

I think first it worth have a look again in how variables work (in a more illustrative and informal way). First a variable has a type, which determines how the bytes stored in that variable will be interpreted. The type also determines the amount of memory necessary for that variable.

Let's say we want to declare an integer variable (in C):

int x;
This variable (assuming it is an int 32 bits) will use 4 bytes of memory; this means that it can store up to 232 possible values (not all of then at the same time obviously). And what about the memory, how is it being used by the variable x? Let's think of the main memory as a huge array (once again I want to be informal) divided in blocks of 8 bits - 1 byte. As an array, each byte can be accessed by an index, actually each byte in that 'array' has an unique index called memory address through which we can access the contents stored in that piece of memory.

Let's imagine that 
the memory address 0x100 has been reserved for the variable x  - that piece of memory would look like this:



As said before, the variable x, as a 32 bits integer, is using 4 bytes starting at the address 0x100, which we say is the address of that variable. So, knowing the start address and the type, we can 'visualize' the memory space used by that variable and verify that it uses four consecutive bytes starting at 0x100.

If we assign a value to x, say 27 (0x1B in hex), the memory space would look like this:

x = 27;


The LSB (Last significant Byte) is in the smallest address of the four bytes being used by the variable x. This is due to the fact I'm considering a Little-endian architecture in this example - used by popular PCs nowadays.

Now that we have a basic idea about variables, let's talk about pointers. In some extent, pointers are like normal variables. They have a type, a name and need memory space to store the data assigned to it.

But this starts to change a little bit when we look on what type of information does a pointer variable stores. Basically a pointer stores a memory address. So in part we can think on it as a index variable (remember that we can think of the memory as a big array). This memory address can be the address of dynamically allocated memory, of a variable and even the address of a function - which we can talk about later in another post.

In a 32 bits architecture an memory address is a number that uses 32 bits of space, so a pointer will use 4 bytes. Let's go to a simple example. Considering our x variable - whose address is 0x100 - lets assign its address to a pointer

int *p = &x;
Before going any further, lets briefly talk about the symbols being used here. When declaring a pointer variable in C or C++, what distinguishes such a variable from a normal one is the asterisk (*) symbol put on the left of the variable's name. The ampersand symbol (&) when put on the left of a variable is used to get the address of that variable. So in this single line we are declaring a integer pointer called p and assign to in the address of the variable x.




In our picture now, what we have is a int variable x, whose address is 0x100, and the int pointer p pointing to the same memory address. Now, as the pointer 'knows' the address where the variable x stores its data, we can manipulate the data indirectly using the pointer. For instance consider the line bellow:
*p = 30;

What happens is that the variable x no longer has the value 27, instead we change its contents to 30 using the pointer.

Before ending this very basic discussion about pointer, a little bit of C, C++ symbology.

int *p
Here the * symbol is being used to say the p is a pointer (int pointer)

p = 30;
A pointer always interpret the data assigned to it as a memory address. So in the case we are telling the pointer to point to the address 30 - which is likely to cause problems and seems wrong as we are not sure what is being store there.

p = &x;
Now we are assigning the address (&) of x into p - note that p without the *, as written above, everything we assign to a pointer will be treated as a memory address.

*p = 20;
Now look the asterisk! It tells the pointer to assign 20 into the memory being pointed by it, we are not telling the pointer to point to the address 20.

So the asterisk when used in a variable declaration, tells the compiler that it is a pointer. However when used in the middle of the program it tells to the pointer: assign this value in the memory being pointed by you!

I think it is enough by now. More coming soon...




Wednesday 16 February 2011

My first new blog

So today I finally decided to expend some time writing down about things that I like. The aim is also to, writing those things, help me remember when I forget then. Things here can be some thoughts, concepts and theories etc... basically around topics like computer science, math and music.

The name came from two things I do and like most: I'm software engineer writing my programs in C#. C# in music is also the note C half tone higher. Music, and more specifically guitar, is the other thing I have been doing for, more or less 17 years. And just to play a bit with these words, in music D flat, which is the D note half tone bellow, produces the same sound as C#, they are enharmonically equivalent.

Using logarithms to solve fractional exponents


Other day I was studying logarithms in a basic level math course that revisited almost everything we were supposed to learn at high school when I was shocked to see how one of its properties could be easily applied to solve fractional exponents. I confess that I felt thrilled when I saw it.

Basically the property used to solve it is the one that states that:

log282 = 2.log28
Just to check this equality, the solution of both sides give us:

 log282 = log264 = 6
to obtain 64, 2 must be raised to the exponent 6

2.log28 = 2.3 = 6
So in both cases we get the same result - the property is true!

Now what about this:

y = 251/2 ?
We know this is equivalent to the square root of 25, but lets solve it using logarithms

The equality signal (=) was originally a representation of a balance scale. Both sides have to have the same "weight" to keep the balance. So, whatever we do in one side, we also do in the other.
log y = log 251/2
Applying the property we get:
log y = 1/2 log 25
Let's now define the base of the logarithm. In this case, base 5 seems quite convenient:
(It is important to remember that the base we choose must be the same used by all logs in our equation)
log5 y = 1/2 log5 25 
log5 y = 1/2 . 2
log5 y = 1
y = 51 
y = 5
Now lets consider a more complete example using almost all properties of logarithms - which can be checked out here
Adding the log in both sides we get:
Now using the properties - when a number is divided we subtract the log of both and when a number is multiplied we add - our equation gets the form:
log h = log (81)1/3 + log (27)1/2.5 - log (243)1/10
It is clear from the example that the numbers 81, 27 and 243 are all power of 3, so it will be chosen as the base.
log3 h = log3 (81)1/3 + log3 (27)1/2.5 - log3 (243)1/10
log3 h = 1/3 log3 (81) + 1/2.5 log3 (27) - 1/10 log3 (243)
Reckoning the logs at the right side we get


log3 h = 1/3 4 +  1/2.5 3 - 1/10 5
log3 h = 1.33 + 1.2 - 0.5
log3 ˜ 2

Reckoning the inverse of the logarithm, the exponentiation we get the final result - approximate

h ˜ 32
h ˜ 9


Voilà, logarithms are really a powerful tool, thanks to John Napier!