2013-11-02

Meia vida


Uma amiga minha disse estar tendo dificuldades em entender o conceito de meia vida e que até o professor dela se confunde nas explicações.

Mas meia vida não é tão complicada assim.

Primeiro vamos entender uma coisa: físicos, engenheiros e químicos gostam de complicar as coisas, de criar fórmulas complicadas a serem decoradas. Já os matemáticos são conhecidos como os preguiçosos da ciência: sempre procuram a forma mais fácil de resolver os problemas.

Por sorte, meia vida é um problema matemático!

Para químicos e físicos, meia vida é um decaimento exponencial, o período de semidesintegração de um isótopo para desintegrar metade de sua massa; para matemáticos, não passa de uma função.

Complicado? Nem tanto…

Os professores gostam de uma fórmula de sete cabeças:

 N  = e-λ·t
 N0             

Enrolado, não?

— Não!

A fórmula parece complicada porque foi dada antes do conceito ter sido compreendido. Então, vamos recomeçar do zero.

De modo simples, meia vida é o tempo que leva pra uma certa quantidade de uma substância radioativa se reduzir à metade.

Ou seja, se 1kg de uma substância X se desintegra e, em 20 anos, sobram 500g (a metade), o tempo de meia vida é de 20 anos.

A parte legal é que, em mais 20 anos (40 anos no total, 2 × meia vida) terá se reduzido à metade de novo, 250g, ou seja, 1/4 do original.

Daí deduzimos que cada vez que se passa o período de meia vida, a quantidade se reduz pela metade de novo.

Então considere:
  • m = massa em relação à quantidade original.
  • t = quantidade de unidades de meia vida passados – por ex., se a meia vida é 20 anos e se passaram 50 anos, t é igual a 50 / 20 = 2.5.

A fórmula fica muito simples:

m =  1 
        2t

Simples, não?

Vamos a um exemplo: digamos que um elemento de meia vida de 68 anos tenha perdido 10% de sua massa. Quanto tempo levou?

A massa atual 10% menor que a original, ou seja: 1 - 0,1 = 0,9. Podemos usar isso em nossa fórmula:

_9_ =  1 
 10      2t

Podemos inverter as frações:

         10_ = 2t
9

É uma equação fácil de resolver, precisamos apenas aplicar logaritmo binário:

log2(10/9) = log22t

log2(10/9) = t

t = 0,152

Então se passou 0,152 do período de meia vida. Como sabemos que a meia vida é de 68 anos, o tempo transcorrido foi de:

0,152 × 68 anos = 10 anos e 123 dias aproximadamente

Não é tão complicado, ou é? Matemática simples.

O truque é tentar lidar com o problema em etapas, sem se preocupar com a complexidade geral.

[]’s
Cacilhας, La Batalema

2013-10-20

Coerência é para os fracos

Baal Façamos um exercício de lógica:

Desejar a morto de alguém é apologia ao assassinato.

Assassinato é crime e a apologia ao crime também é considerada crime.

Portanto, ao dizer “bandido bom é bandido morto”, a pessoa comete o crime de apologia ao assassinato, portanto, é também uma criminosa, por definição.

Assim, segundo meu jeito de encarar a questão, vocês que dizem “bandido bom é bandido morto” deveriam ser julgados perante a lei. Segundo o jeito de vocês mesmos de encarar a questão, vocês deveriam ser sumariamente assassinados, pois, como vocês dizem, bandido bom é bandido morto.

Pensem nisso com carinho.

[]’s
Cacilhας, La Batalema


Facebook

2013-10-14

Tipagem de dados em programação

Heim? Eu já havia determinado que assuntos de programação seriam publicados no Kodumaro, deixando este blog pro meu blá-blá-blá habitual.

No entanto surgiu um assunto sobre programação que é, ao mesmo tempo, reclamação minha.

Sei que programadores de linguagens de tipagem fraca e dinâmica e programadores de linguagens de tipagem forte e estática têm dificuldade em diferenciar tipagem fraca de dinâmica e tipagem forte de estática, porém isso está chegando a um extremo de eu ler essa confusão em livros didáticos!

Chega dessa confusão, vou tentar explicar um pouco.

Resistência a coerção

Toda linguagem de programação possui tipos de dados e coerção ou conversão entre tipos. Quanto mais variados e bem definidos os tipos da linguagem, mais difícil é a coerção entre eles e diz-se que a linguagem é mais forte. Muitas linguagens de tipagem forte chegam a requerer um coerção explícita, chamada typecasting.

Linguagens com poucos tipos ou cuja diferença entre os tipos seja fraca, são chamadas de tipagem fraca.

Por exemplo, duas linguagens de tipagem fraca são Javascript e Lua:
value = 12
value = value + "2"

A sentença acima é válida tanto em Javascript quanto em Lua e, nas duas, o valor final da variável value é 14.

Isso acontece porque, como o primeiro parâmetro da soma era um número inteiro, o segundo parâmetro (a string "2") foi implicitamente convertida para seu equivalente numérico.

Esse tipo de mágica pode gerar problemas desagradáveis e erros difíceis de serem depurados, mas é uma abordagem válida se o programador decidir conviver com isso.

Já linguagens de tipagem forte, como Python e Java, geram exceções caso você tente usar um objeto como se fosse de um tipo diferente dele:
>>> value = 12
>>> value = value + "2"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Como você pode ver, Python reclama imediatamente do tipo. É preciso executar uma coerção explícita.

Quem determina o tipo?

Outra questão é, havendo tipos definidos, quem determina o tipo.

Se o tipo de um dado é determinado por seu container, a variável que o referencia, a tipagem é dita estática. Por exemplo, Java e C são linguagens de tipagem estática.

Já quando o próprio dado já possui seu tipo auto-contido, independente de quem o referencie, a tipagem é chamada dinâmica. Python e Erlang possuem tipagem dinâmica.

Agora, repare uma coisa: uma linguagem ser forte ou fraca não tem nada a ver com ela ser estática ou dinâmica. Vimos diversos exemplos:
  • Lua e Javascript possuem tipagem fraca e dinâmica.
  • Python e Erlang possuem tipagem forte e dinâmica.
  • Java possui tipagem forte e estática.
  • C possui tipagem fraca e estática.
Sim! A tipagem de C é fraca e estática, ao contrário do que muita gente pensa. A coerção entre tipos de C é muito simples, basta você usar ponteiros de tipos diferentes para referenciar o mesmo valor – mesmo que o resultado não seja o esperado por quem programa em outras linguagens de tipagem fraca:
char var_1[] = "A";
unsigned char *var_2;
var_2 = var_1;

O valor de *var_1 será a string "A", enquanto o valor de *var_2 (ponteiro que aponta para o mesmo dado na memória) será 65. O tipo é atribuído pelo ponteiro/variável.

Portanto, ao contrário do que muita gente prega, uma linguagem pode ter tipagem estática e fraca sim.
[update 2013-10-16]
O valor de *var_2 ou var_2[0] será 65, mas o valor de var_2[1] será 0.

Isso ocorre porque em C strings são listas de caracteres terminadas com nulo (\000).
[/update]

Creio que isso possa ter esclarecido algumas coisas que as pessoas repetem por aí à moda Goebbels.

[]’s
Cacilhας, La Batalema

2013-08-09

O programador positivo

Kenpachi Artigo muito bom tirado do blog Randall Degges – Random Thoughts of a Happy Programmer:

Is it just me, or is the technical community developing a more and more negative outlook in recent years? I hate to complain, but it seems like every week the development community is up in arms about some huge outrage, whether it be regarding code of conduct policies, sexism, startup criticism, craftsmanship, or any other topic.

If you’re a programmer and stay up-to-date with community happenings via Hacker News, you’ll almost certainly notice a trend: there are lots of popular articles focusing on the negatives (mean rants, public shaming, outrage about various issues, etc.). And if you happen to participate in article discussion, you’ll get an even greater taste of the negative attitudes becoming more and more pervasive in the community: articles flooded with a mix of slanderous (and more frequently, downright mean) comments that really bring everyone down =/

Personally, I like to focus on the positive. ^^

The Problem with Negativity

My problem with negativity comes primarily from personal experience. I wasn’t always as happy as I am now, and I certainly didn’t have a positive attitude most of my life.

Several years ago I had just left university (I dropped out after my second year of computer science), and decided to start working in the field. While I’ve always loved programming, throughout my university experience I was one of the most negative people I’ve known. I was extremely judgemental, short of temper, and generally quick to dismiss other people and their ideas.

When I left school and started working in the field I realized exactly how miserable I really was: instead of being able to enjoy every day, enjoy my relationships, and enjoy my work – I was instead overly focused on the negatives: how unfair things were, how I deserved more, how other people were causing problems for me, and how I was vastly superior to everyone else.

I distinctly remember coming home from work and sitting in the bathtub one day, thinking about myself, and where I wanted to be in five years. The first (and only) thing that immediately came to mind was that I wanted to be a better person: I wanted to be smarter, more successful, and happy.

It wasn’t until that moment I realized that I was truly unhappy with my current self, and really needed to make some serious personal changes if I could ever enjoy my life. Being discontent with yourself is a horrible feeling. You feel angry, frustrated, and cheated. Am I doing something wrong? Why do I feel this way? Without realizing it, I had been turning my internal frustration and anger outwards, with horrible consequences.

It was at that moment I decided to actually focus on real personal development. Instead of allowing myself to play the victim and slowly let my frustration and anger eat away at me, I decided to take my future into my own hands and make whatever changes necessary to make myself a better person.

The Positive Programmer

In the beginning I had a really difficult time training myself to let go of my bad habits and negativity. Your personal outlook and mental response to every day situations is something that comes naturally. It takes a lot of energy, education, and practice to let go of bad behaviors and teach yourself new (healthier) behaviors.

After doing some basic Google research: How can I be happy?, How can I become a better person?, etc. – I realized that I needed to start out by re-educating myself. It’s very difficult to find answers to questions you don’t yet know.

The first thing I did was randomly pick a few highly reviewed personal development books on Amazon and read them. Instantly, I began to realize that improving yourself as a person is all about being positive.

Instead of focusing on the negative in life, focus on the positives. One of the most important truths I’ve learned came from my study of minimalism.

What is happiness really? Happiness is being content with yourself and your surroundings. What’s the best way to be content with yourself and your surroundings? To accept reality as it is.

All feelings of frustration, anger, and negativity are generated internally. If you’re driving down the freeway and another driver cuts you off, forcing you to slam on your brakes to avoid a collision – most people would get angry at the other driver. It’s a natural reaction, after all. The person ahead of you did something they shouldn’t do, which caused you an inconvenience. In your mind, they’ve done something that doesn’t align well with your version of reality, so your brain makes you feel angry and frustrated.

The simplest way to avoid getting angry and frustrated (not only with yourself, but with others as well) is to practice compassion. Instead of viewing the world through your own point of view, play the role of a calm observer. Accept the behavior of others as it is, and don’t allow yourself to project your desired behavior onto others. Instead of allowing yourself to get angry over situations you can’t control, learn to calmly accept them and carry on.

The ability to rationally analyze situations and make mindful decisions will not only help you maintain a positive outlook on life, but will help you feel happier, and allow you to focus on more important topics on a day to day basis.

Instead of wasting energy getting upset and angry with others, you can instead focus on doing the things that are important to you:
  • Enjoying your relationships.
  • Fully enjoying your work.
  • Taking control of your life and growing as a person.
Since I decided to invest time in making myself a better person, I’ve completely changed my day-to-day attitude, behavior, and outlook. Instead of feeling unhappy and discontent with myself, I’ve been able to build a great life that allows me to really enjoy each day.

Some Closing Thoughts

Living with a negative attitude is a horrible burden, something I wouldn’t wish on anyone. It really pains me to see so many of my peers stuck in a continuous cycle of negative thinking. Focusing on the negatives is the simplest way to:
  • Make yourself unhappy.
  • Sacrifice your personal development and growth.
  • Miss out on great opportunities and obvious ways to become a better person.
  • Alienate yourself from other great people doing great things.
My advice to you if you’re stuck in a rut like I was: make a commitment to yourself to focus on personal development – it’s never too late to get started.

Is it easy to recondition yourself? No way. It will be a slow process: nothing will happen overnight.

Take small steps. Here are some great ways to get started:
  • Pick up a good personal development book. Some good starting topics to research are minimialism, mindfulness meditation, happiness, procrastination, and talent. If those don’t sound immediately appealing, try reading a biography on someone you greatly respect.
  • Be mindful of your thoughts throughout the day. The next time you find yourself thinking What the hell is that person doing? take a second to think about why you feel that way. Are you angry? Are you overreacting? Don’t be angry with yourself, just acknowledge your thoughts and make a mental note of why you felt that way.
  • Remove negativity from your immediate surroundings. Easy ways to get started are to unfollow people on twitter who continuously tweet negative things, stop reading news, and don’t participate in negative conversations with friends and family.
  • Keep your goal in mind at all times. Throughout the day you should tell yourself (especially when you’re feeling negative) that your goal is to become a better person, and the only way to do that is to consciously work at it! If you need motivation, don’t feel bad about getting help: watching motivational videos, listening to your favorite songs, etc.
Reconditioning yourself to be a more positive person is no easy task, but I can tell you from experience that it’s worth every bit of effort you put into it. Changing your behavior is possible with enough focus, motivation, and rational thinking.

If you’re stuck in a rut and want someone to chat with, feel free to shoot me an email, I’d love to help!

Published: Tue 26 March 2013

2013-07-05

Plebiscito

Baal

Lembram daquele ditado do comercial sobre o brasileiro não desistir nunca? Pois é, para uma melhor verossimilhança, precisamos alterá-la um pouco:


Sou brasileiro e não aprendo nunca.


Eu, o brasileiro que não aprende nunca, lutei para melhorar o cenário sócio-político de meu país e o governo propôs mudanças.

Mas essas mudanças são apenas um primeiro passo em direção ao que buscamos, não um salto quântico que nos leva magicamente ao destino final.

Então, eu, o brasileiro que não aprende nunca, me revolto contra as mudanças e faço de tudo para darmos um passo atrás! Afinal de contas, pra mim, o brasileiro que não aprende nunca, ter do que reclamar é muito mais importante do que progredir gradualmente.

[]’s
Cacilhας, La Batalema