• C++ Programming for Financial Engineering
    Highly recommended by thousands of MFE students. Covers essential C++ topics with applications to financial engineering. Learn more Join!
    Python for Finance with Intro to Data Science
    Gain practical understanding of Python to read, understand, and write professional Python code for your first day on the job. Learn more Join!
    An Intuition-Based Options Primer for FE
    Ideal for entry level positions interviews and graduate studies, specializing in options trading arbitrage and options valuation models. Learn more Join!

Proving your Programming Skills

General idea

A = a
B = b

A = A*B = (ab)
B = b

B = A/B = (ab/b) = a
A = (ab)

A = A/B = (ab/a) = b

A = b
B = a
 
To be quite blunt, how does swap() prove you can program! It's so K&R..

There's more to life than that.


1. If a and b are double, who cares?
2. It they are array, use std::move.
 
nope! you are using two extra temp variables A & B
a and b are given, you have no more resources

no i meant a and b as the values themselves, i shouldve clarified.

A, B are the var names.

example

int A = 4
int B = 5

A *=B -> A = 20
B = A/B -> B = 4
A = A/B ->A= 5

now A = 5, B = 4
 

I'm being pedantic, 'program' is the wrong word (use 'variable'), but was copied verbatim..

a=a+b;
b=a-b;
a=a-b;

I have a nasty feeling that several(3?) temp variables are generated by the compiler. Am I missing something??

And two arithmetic operations! Yikes. Take and b close to each other to get catastrophic cancellation. Round-off errors are also possible.

BTW that nameless blog looks like cookie spam.


//Now try it with matrices!
 
Last edited:
Example of round off.

C++:
// Roundoff.cpp

// DD

#include <iostream>
#include <iomanip>

namespace NOT_STL_SWAP
{
    template <typename T>
    void swap(T& a, T& b)
    {
        a = a + b; // a += b !!
        b = a - b;
        a = a - b;
    }

}

int main()
{
    using NOT_STL_SWAP::swap;

    float a = 1.0F;
    float b = 1.0001012345679F;

    int N = 1;
    for (int n = 1; n <= N; ++n)
    {
        swap(a, b);
    }
    std::cout << std::setprecision(8) << a << ", " << b << '\n';

    a = 1.0F;
    b = 1.0001012345679F;
    for (int n = 1; n <= N; ++n)
    {
        std::swap(a, b);
    }
    std::cout << std::setprecision(8) << a << ", " << b << '\n';

    return 0;
}
 
C++:
namespace YET_NOT_STL_SWAP
{
    template <typename T>
    void swap(T& a, T& b)
    {
        a * / b;
        b = a / b;
        a = a / b;
    }

}
no i meant a and b as the values themselves, i shouldve clarified.

A, B are the var names.

example

int A = 4
int B = 5

A *=B -> A = 20
B = A/B -> B = 4
A = A/B ->A= 5

now A = 5, B = 4

Have you tried this in real life? * and / are slow and inaccurate.
 
Last edited:
Back
Top