Prabakaran Blogs

Free IIT Economics / Stock market Video Courses

 

Free video courses from IIT on economics and stock market

Population and Society

Security Analysis and Portfolio Management

History of Economic Theory

September 8, 2012 Posted by | Uncategorized | Leave a comment

World undergoes transformation

World is undergoing profound transformations in the recent decades on economic and social ground. In 1900, Europe’s population is almost a quarter (against 60% of Asia). Now, the entire West contains not more than 12% of the world’s population but still dominates the world. In 1900 it could be said that the West was “superior” in many fields, including institutions, industrial systems, education, and technological innovations. Now, this superiority is now under challenge from the emerging East.

Economic crisis in western countries is because of materialistic nature of social life(consumerism) which is pushing people to buy (borrow) based on tomorrow’s effort(debt). Debt in most of the western countries is so high and deficit could be managed only by acquiring more and more debt. In order to get out of this economic crisis, western countries started adopting eastern philosophies and spiritualism to get away from materialistic attachment.
In the following TED talk, Hans Rosling (Swedish statistician on public health) talks about Asia regaining its dominance in the world with amazing statistics

August 24, 2012 Posted by | finance | Leave a comment

Avoid locking in Singleton

The Singleton is a useful Design Pattern which allows only one instance of your class. Singleton is implemented by declaring static instance of the object reference within the class

class MySingleton {
static MySingleton *instance;
MySingleton() {
//...
}

public:
MySingleton* getInstance() {
return instance;
}

}

static MySingleton::instance= new MySingleton();

If singleton object is created during loading time itself, no locking is required. But in case of lazy loading, it needs to be guarded with a mutex to avoid multiple object instantiation.

MySingleton* getInstance() {

 //acquire mutex
if (NULL == instance) {
instance = new MySingleton();

 }

  //release mutex
return instance;
}

Every request to getInstance() includes mutex overhead.In order to avoid mutex overhead, double checked locking pattern can be used.

// Double-checked locking -- don't use
MySingleton* getInstance() {
if (NULL == instance) {
//acquire mutex
if (NULL==instance) {
instance = new MySingleton();
}
//release mutex
}
}

This method is not 100% safe because of compiler optimizations and may lead to undefined behavior which is hard to debug. Another technique(safe to use) is to use atomic operations and local variable as specified below.


MySingleton* getInstance() {
MySingleton *localRef = new MySingleton();

  int ret = testandset(&instance, 0, localRef);

  //note testandset function returns old value stored in the variable.
if (0==ret) {
return instance;
}
//some other thread had initialized this.

  delete localRef;

  return instance;
}

July 28, 2012 Posted by | design | Leave a comment

SOLID Design Principles

SOLID is acronym introduced by Robert C Martin, which stands for five basic principles of object oriented programming/design.

Single Responsibility Principle:
Every class should have a single responsibility, and that responsibility should be entirely encapsulated by the class.

Open Closed Principle:
Software entities (classes, modules) should be open for extension, but closed for modification.

Liskov Substitution Principle:
If S is a subtype of T, then objects of type T in a program may be replaced with objects of type S without altering any of the desirable properties of that program.

Interface Segregation Principle:
Split interfaces which are very large into smaller and more specific ones so that clients will only have to know about the methods that are of interest to them.

Dependency Inversion Principle:
Decouple high-level components from low-level components such that reuse with different low-level component implementations becomes possible.

July 1, 2012 Posted by | Uncategorized | Leave a comment

Symptoms of bad design

Code Refactoring is the process of changing a software system in such a way that it does not alter the external behavior of the code yet improves its internal structure-Fowler. In order to identify whether legacy software product requires code refactoring, one needs to know whether the existing system design is good or bad. The knowledge of bad design symptom also assists the designer to perform better.

Following are the symptoms of bad design

Rigidity: code/design is hard to change. Simple change requires lot of code changes.

Fragility: code/design is easy to break. code break in unexpected area.

Immobility:Hard to re-use code.

Viscosity:Make easier changes (hack) than fixing issues in-line with the current design.

Complexity: Too much anticipation of future need.

Repetition: Similar code in many places with slight change.

Low Cohesion: Less degree of connectivity among the elements of single class.

High Coupling: Interdependency between modules.

June 30, 2012 Posted by | design | Leave a comment

Sample Personal Financial Plan

One of the most important thing to track in our life is our personal financial status. We do not give much importance to it (like running a business), because we are not accountable to any one for our personal financial goals and results.

Financial Plan helps you assess where you are now financially and will help you to reach your financial goals in the near future. This excel financial plan template allows you to plan and analyze the following

  • Cash Flow Analysis – lists your income and expenses and calculate net cash flow(Subtract your expenses from your income). If it’s positive, plan how to invest in various financial instruments with the excess. If it’s negative, either find ways to increase your income or cut your expenses
  • Percentage Allocation of excess money in various investment instruments
  • Asset/Debt Ratio – lists your asset and debt and calculate net worth
  • Pension Requirement – capital erosion calculation and pension requirement

Excel template contains four sheets.

First sheet contains percentage of increase for every asset type such as stocks, FD, Pension, House, Plot(Land) etc.
Second sheet captures income, expense and savings in various financial investment instruments
Third sheet captures total asset, debt and net worth.
Fourth sheet captures retirement planning.

Personal Financial Plan (Right click and save as)

Note: Do not modify values under colored cells(red) as they are computed automatically.
Unit is in Thousands

Sample Strategy for planning
1.Insurance perspective: (ordered with priority)

  • If you do not have 25 lakhs(based on your lifestyle) net-worth today,buy term insurance for 25 lakhs
  • Buy 1 house and rent it out(occupy this house if need arises)
  • Buy at-least 1 acre land to produce food organically

2.Growth Perspective:

  • Choose financial instrument such as stock/PPF/MF where is no long term capital gain tax (>1 year) during employment if your tax bracket is 30%
  • Set networth target for next 10 or 15 years and distribute savings in appropriate investment instrument to achive the target.

3.Retirement Perspective:

  • Plan to retire by 50. Divert 50 lakhs to debt based financial instrument(no equity exposure to ensure safety of money) and Invest additional 2 lakh for next 10 years such that it triples with 9% cumulative growth rate.
  • PF+PPF+Pension+Bank Balance at the age of 50 should be close to 50 lakhs such that immovable and equity based assets are not disturbed to draw pension
  • Buy safe pension annuity with this amount (~1.5 crores) with mix of Post office monthly income plan, senior citizen saving scheme,New pension annuity scheme etc till tax ceiling limit is reached
  • Make sure that pension withdrawn does not erode the capital and will adjust inflation . Expense such as rent/food will be reduced during this phase.Only major expense head will be medical which should be covered by medical insurance plan.

4.Additional Income:

  • Additional income is generated with stock dividend which are not taxable
  • Additional income can also be generated, with 12 dividend based mutual fund maturing each month. Note that these are not taxable.
  • Investment in land can be utilized for agri/business to produce additional income. Note agricultural income is not taxable. Any business pays taxes after its expense unlike employees where TDS is deducted before expense.

If you find any items missing under income, expense  or  savings head. Please comment.

April 19, 2012 Posted by | finance | 2 Comments

Information processing capabilities of the brain

Brain stores and process information based on the following principles

Photographic: Brain has enormous capacity to remember pictures and images. It is much easier to remember a picture than to remember long lines of text.

Keywords: Brain stores information based on the abstraction principle. After reading long paragraph, brain condenses this information and stores keywords or headlines which abstracts the content in the paragraph.

Stories: It is more important than facts for remembering ideas. Stories capture facts in many different context and aids in retrieving and correlating with many other aspects. “Humans are not ideally set up to understand logic; they are ideally set up to understand stories.” –Roger C. Schank, cognitive scientist

Associations:Brains links different subjects together to create a pattern.  New information feed to the brain will get associated with existing pattern already formed based on the previous information fed to it.

Context: Information fed into the brain is stored based on the context. For example ‘laptop’ is stored in brain with contexts such as when it is bought, who bought it, How much, Where it is bought,etc. Once it is stored in brain it can be retrieved with one of more context values as input.

January 1, 2012 Posted by | thinking | Leave a comment

Skills for the 21st century

Trend in past centuries

Agricultural Age – 18th Century

Industrial Age – 19th Century

Information Age – 20th Century

Conceptual Age – 21st Century

Education systems are designed during the Industrial age and it produced workers for factories. Core subjects covered under schools during this century are

  • English – Reading, Writing and Language arts
  • Mathematics
  • Science
  • Geography
  • History
  • Government and Civics

We are still following these traditional education systems.  It is not sufficient to make few changes to fit for 21st century, rather it requires a complete transformation in order to equip human capital for the 21st century.

The Partnership for 21st Century Skills was formed in 2002 by U.S. Department of Education with fortune companies such as Apple, Cisco, Dell, Microsoft, SAP, etc that advocates for 21st century readiness for every student. P21 advocates to promote understanding of academic content at much higher levels by weaving 21st century interdisciplinary themes into core subjects such as Global Awareness, Financial,Economic, Business and Entrepreneurial Literacy, Health Literacy and Environmental Literacy

Apart from core subjects and 3 Rs (Relating, Representing and Reasoning), following skills(4Cs) are mandatory for students of 21st Century

  • Creativity and Innovation
  • Critical Thinking and Problem Solving
  • Communication
  • Collaboration
  • Information, Media and Technology Literacy
  • Life Skills
    • Flexibility and Adaptability
    • Initiative and Self Direction
    • Social and cross cultural Skills
    • Productivity and Accountability
    • Leadership and Responsibility

For more information on tools and resource provided by P21 refer here

December 18, 2011 Posted by | education | Leave a comment

Power of Brain

Many of us think that calculators are more powerful when compared to our brains simply because they can perform calculations at incredible speeds with flawless accuracy.

Here comes the genius Arthur Benjamin who demonstrates the memory and processing speed of brain in this TED lecture and disproves the myth.

July 28, 2011 Posted by | thinking | Leave a comment

Assembly code level optimization Technique

Optimizing at the code level is not effective as higher-level optimizations. Memory allocation optimizations, algorithmic optimizations should be tried before trying out the code level optimization. Code line level optimization is performed based on the assembly instruction created for one line of source code or one function. This needs to be done with the help of assembler and disassembler.

The output of the compiler (object file and executable) should conform to standard format so that it shall be run by the operating system. This format is called ELF (Executable and linking format) and all compilers output including FORTRAN, C, C++, etc will conform to this format. It defines how an executable file is organized so that loader knows where to look for code, data, etc.

Analyzing the assembly instructions is tricky and it requires knowledge about the assembly language. To get primitive understanding of how the C source code gets transformed to assembly language, you can use objdump tool

For example, consider the following program (fact.c)

#include <stdio.h>
int factorial(int number)
{
    if (number >12) return(1);
    int fact =1;
    int i =1;
    for (; i<=number; i++)
    {
        fact = fact * i;
    }
    return fact;
}
int main()
{
   printf(“%d\n”, factorial(12));
   return 0;
}

Compile the above code with debugging enabled(-g option)

$gcc -g -c fact.c
Objdump -S option displays both the source code and its corresponding assembly instructions together. This will help us to understand how C code is transformed to assembly by the compiler.

$objdump -S fact.o
fact.o:     file format elf32-i386
Disassembly of section .text:
00000000 <factorial>:
#include <stdio.h>
int factorial(int number)
{
   0:   55                      push   %ebp
   1:   89 e5                   mov    %esp,%ebp
   3:   83 ec 14                sub    $0x14,%esp
    if (number >12) return(1);
   6:   83 7d 08 0c             cmpl   $0xc,0x8(%ebp)
   a:   7e 09                   jle    15 <factorial+0x15>
   c:   c7 45 ec 01 00 00 00    movl   $0x1,0xffffffec(%ebp)
  13:   eb 2c                   jmp    41 <factorial+0x41>
    int fact =1;
  15:   c7 45 f8 01 00 00 00    movl   $0x1,0xfffffff8(%ebp)
    int i =1;
  1c:   c7 45 fc 01 00 00 00    movl   $0x1,0xfffffffc(%ebp)
    for (; i<=number; i++)
  23:   eb 0e                   jmp    33 <factorial+0x33>
    {
        fact = fact * i;
  25:   8b 45 f8                mov    0xfffffff8(%ebp),%eax
  28:   0f af 45 fc             imul   0xfffffffc(%ebp),%eax
  2c:   89 45 f8                mov    %eax,0xfffffff8(%ebp)
  2f:   83 45 fc 01             addl   $0x1,0xfffffffc(%ebp)
  33:   8b 45 fc                mov    0xfffffffc(%ebp),%eax
  36:   3b 45 08                cmp    0x8(%ebp),%eax
  39:   7e ea                   jle    25 <factorial+0x25>
    }
    return fact;
  3b:   8b 45 f8                mov    0xfffffff8(%ebp),%eax
  3e:   89 45 ec                mov    %eax,0xffffffec(%ebp)
  41:   8b 45 ec                mov    0xffffffec(%ebp),%eax
}
  44:   c9                      leave
  45:   c3                      ret

00000046 <main>:
int main()
{
  46:   8d 4c 24 04             lea    0x4(%esp),%ecx
  4a:   83 e4 f0                and    $0xfffffff0,%esp
  4d:   ff 71 fc                pushl  0xfffffffc(%ecx)
  50:   55                      push   %ebp
  51:   89 e5                   mov    %esp,%ebp
  53:   51                      push   %ecx
  54:   83 ec 14                sub    $0x14,%esp
   printf(“%d\n”, factorial(12));
  57:   c7 04 24 0c 00 00 00    movl   $0xc,(%esp)
  5e:   e8 fc ff ff ff          call   5f <main+0x19>
  63:   89 44 24 04             mov    %eax,0x4(%esp)
  67:   c7 04 24 00 00 00 00    movl   $0x0,(%esp)
  6e:   e8 fc ff ff ff          call   6f <main+0x29>
   return 0;
  73:   b8 00 00 00 00          mov    $0x0,%eax
}
  78:   83 c4 14                add    $0x14,%esp
  7b:   59                      pop    %ecx
  7c:   5d                      pop    %ebp
  7d:   8d 61 fc                lea    0xfffffffc(%ecx),%esp
  80:   c3                      ret

Even if you do not know assembly instructions, you can still use this technique to improve the code by counting the total number of assembly instructions produced for a function before and after your code changes.

Compiler(gcc) also provides -S option to stop processing after it produces an assembly file.

Consider the following program t1.c

#include<stdlib.h>
typedef struct element
{
    int              val;
    struct element  *next;
} Element;
Element *head;

void insert(int no)
{
    Element *newNode = (Element *) malloc( sizeof( Element ) );
    newNode->val = no;
    newNode->next = NULL;
    if (NULL == head) { head = newNode; return ;}
    Element *iter = head;
    while (NULL != iter->next) iter = iter->next;
    iter->next = newNode;
    return;
}
int main()
{
    insert(10);
    return 0;
}
Generate the assembly file for the above program as follows

$gcc -O2 -S t1.c
gcc will produce an assembly output file whose file name is the same as the original c file (t1 in this example) with a .s suffix. It will display a long output, so it is better to redirect it to a file.

The output file contains the following

        .file   “t1.c”
        .text
        .p2align 4,,15
.globl insert
        .type   insert, @function
insert:
        pushl   %ebp
        movl    %esp, %ebp
        subl    $8, %esp
        movl    $8, (%esp)
        call    malloc
        movl    head, %edx
        testl   %edx, %edx
        movl    %eax, %ecx
        movl    8(%ebp), %eax
        movl    $0, 4(%ecx)
        movl    %eax, (%ecx)
        jne     .L8
        jmp     .L11
        .p2align 4,,7
.L5:
        movl    %eax, %edx
.L8:
        movl    4(%edx), %eax
        testl   %eax, %eax
        jne     .L5
        movl    %ecx, 4(%edx)
        leave
        .p2align 4,,2
        ret
.L11:
        movl    %ecx, head
        leave
        ret
        .size   insert, .-insert
        .p2align 4,,15
.globl main
        .type   main, @function
main:
        leal    4(%esp), %ecx
        andl    $-16, %esp
        pushl   -4(%ecx)
        pushl   %ebp
        movl    %esp, %ebp
        pushl   %ecx
        subl    $4, %esp
….
The insert function has approximately 25 instructions with three branches.

If the program implements simple linked list, then we shall modify the program as follows (t2.c)

#include<stdio.h>
#include<stdlib.h>
typedef struct element
{
    int              val;
    struct element  *next;
} Element;
Element *head;
void insert(int no)
{
    Element *newNode = (Element *) malloc( sizeof( Element ) );
    newNode->val = no;
    newNode->next = head;
    head = newNode;
    return;
}
int main()
{
    insert(10);
    return 0;
}
Generate the assembly instruction

$gcc -O2 -S t2.c
t2.s contains

        .file   “tt.c”
        .text
        .p2align 4,,15
.globl insert
        .type   insert, @function
insert:
        pushl   %ebp
        movl    %esp, %ebp
        subl    $8, %esp
        movl    $8, (%esp)
        call    malloc
        movl    8(%ebp), %edx
        movl    %edx, (%eax)
        movl    head, %edx
        movl    %edx, 4(%eax)
        movl    %eax, head
        leave
        ret
        .size   insert, .-insert
        .p2align 4,,15
.globl main
        .type   main, @function
main:
        leal    4(%esp), %ecx
        andl    $-16, %esp
        pushl   -4(%ecx)
        pushl   %ebp
        movl    %esp, %ebp

Now insert() function contains only 12 instructions, we have optimized the code to run faster without changing the behavior. This code changes cannot be made if main() assumes that the linked list retrieval is in FIFO fashion.

June 25, 2011 Posted by | Programming | , | Leave a comment

Follow

Get every new post delivered to your Inbox.