Showing posts with label Math. Show all posts
Showing posts with label Math. Show all posts

Wednesday, 6 November 2013

Quick pictures update on ADSR

 Exp.attack at 0.4 and sustain level at 7/8 ( 20 Ms div)




A quick update to show that first try, worked as expected. Spent a few good hours in the process of starting to optimize the different building blocks id gathered, and make them interact. Tried to keep it as readable as possible and document the little quirks, and possible variations, references, etc in the implementation methods.
We have officially an ADSR with variable exponential attack, variable "decay-sustain ratio" ( allows both bypassing the sustain stage, and also looping/extending the sustain stage ), and variable duration/period... For now !


Next comes LFO's from all the wavetables available, simple filters, and start implementing simple convolution reverb. Lets see how far can i  "push the envelope" ( No pun intended).





Square wave and exp.attack at 0.5 ( .2 s Div )


Thursday, 24 October 2013

Richard Feynman, No Ordinary Genius

“Science is like sex: sometimes something useful comes out, but that is not the reason we are doing it. ”
― Richard P. Feynman

Feynman was the anti-thesis of a genius at first glance (highly extrovert, known to work some of his brilliancies in strip club tables, not always a follower of protocols, sassy, and so much more), yet he rubbed shoulders and worked with many of the biggest geniuses of his time.
He also a achieved a Nobel prize ( back in the day where you actually had to earn them, as nowadays they are handing them for your looks and influence to every dick and harry , specially the peace prize!! ), shared with others, for his contributions in light and matter interaction and solved the Space shuttle Challenger explosion in the 80's. All these achievements and other are always epic in proportions by the way he made them happen, adding to the awe of his myth . His extrovert personality only helped to increase the myth around the genius !

There are a few people i could hear lecturing anytime. Herbert Gross, Feynman, Alan V. Oppenheim, Gilbert Strang to mention but a few. Some people do have the gift that makes the difference between learning by memorizing things ( Some seem to spit nothing but book technical terms), and learning by understanding things !





Wednesday, 23 October 2013

Some exercises with the "Caesar cipher" Pt 2.

Plaintext    |a |b |c  |d |e |f  |g |h |i   |j | k | l  | m| n| o | p | q  | r  | s | t  | u | v | w | x | y | z |
P-Number  |0 |1 |2 | 3 |4 |5 |6 |7 |8 |9 |10|11|12|13|14|15 |16 |17|18|19|20|21|22 |23|24|25|
Ciphertext |d |e | f | g |h |i  |j  |k |l |m | n | o | p | q | r  | s| t  | u | v | w | x | y | z  | a | b  | c |

In the Caesar cipher, the modulus operator was used to achieve a fast way of computing the result.
The use of an array from 0 to 25 is inherent to the discrete implementation methods widely used. Look-up tables also get this particularity many a times !
If it is not obvious why, wait until one of the next posts on the subject. Other examples will surely make obvious why .
Let's remember  what was said in a previous post :

// Caesar cipher ==> C = (P+s) Mod (Number_of_Characters)
// Number_of_Characters also known as Keyspace = 26 (0 to 25)
// P = numerical equivalent of character plaintext
// C = Numerical equivalent of cipher text character
// s = number of shifts,adds (n_shift)
// Ke = s = 3 ==> (P+s) mod (Number_of_Characters)
// Kd = -s = -3 ==> (C -s)mod (Number_of_Characters) (reverse operation)

From this, we can then adapt this idea into the way the ascii numerical code uses to represent printable characters.

// Keyspace = 96 ( Nchars; )
// P = retrieved
// s =  n_shift
// [ from "ascii'" character number 32-decimal; 040-OCT; 20-HEX; 00100000-BIN ==> "SPACE" 
// to "ascii'" character number 126 decimal; 176-OCT; 7E-HEX; 01111110-BIN; ==> "~" Equivalence sign - tilde

The way i found was to first subtract  an ascii_offset (retrieved -=32;) compute the algorithm ( uint16_t c =(retrieved + n_shift)% Nchars; ) and then re-add the ascii_offset (retrieved +=32;).

C = (P+s) Mod ( Keyspace )

I should probably note the fact that it should not be confused with the remainder.
Let us see why...

If in C = A modulus B ,  A=13 and B=5 , then C=3 ;
If    C = A remainder B, then it is also C=3.

BUT (and there are always but's) what if we give A=13 and B= -5 ?!
Then, we would get A Modulus B ==> C= -2; In turn, A Remainder B ==> C=3 !!

Oh, yeah !! The art of the Modulus operator in itself  ( specially with only the use of a hand calculator), and its relationship with cryptography, is an art in itself , and can easy allow for a series of posts elaborating on it !
As an example, check the table below (created with Gnumeric) .



Code here
https://docs.google.com/document/d/1CbK-v1OaQIhbr0ao5EY8CrGZ71M9-t4cav4bK4JBwo0/edit?usp=sharing

Friday, 18 October 2013

Prime number generator with arduino

Prime number 1,370,795 from Wolfram Alpha's list

I had to share this Project !
Nick Gammon is a very helpful member on the Arduino forum , and always ready to share his knowledge and help/time .

http://www.gammon.com.au/forum/?id=12168&page=999
http://forum.arduino.cc//index.php?topic=192209.0



Monday, 30 September 2013

Symmetry of waves in wavetable generators and the differences and implications..


The reason why im sharing these wave table generators is because of the fact that some of the ones i found didnt comply with the symmetry of waveforms ( Take the above graph as the correct reference of how they should relate !).
Why is this so important ?! Hmmm, try a guess ?! * Ill leave it to the reader to guess why, as an exercise, as its quite obvious !
Instead they have the period of  the Sawtooth wave starting as 0, when it should be starting at the DC-offset value ( 2047 for a 12-bits DAC, for example).
So, it was starting at PI, instead of zero. Triangle wave were starting at 1.5 PI( which both differences are easy and dirty ways of doing it, but this time didnt satisfy my needs, where i need something correct according to the symmetry for interaction and calculation purposes.
So this was my quick solution to it. I hope to maybe improve on this as soon as i can spare a moment.
Also intend to  do a see-sawtooth ( with more decrement intermediate stages) generator.


// create the individual samples for our Sawtooth-wave table
void createSawTable()
{
  Serial.println(" ");
  Serial.println("Saw table");
  for(uint32_t nIndex = 0;nIndex < WAVE_SAMPLES;nIndex++)
  {
    // normalised to 12 bit range 0-4095
    nSawTable[nIndex] = nIndex * 8;  // == nIndex + (4096/512 == 8);because it   //  never reaches 512
    Serial.println(nSawTable[nIndex]);
  }
}
// create the individual samples for our triangle-wave table
void createTriangleTable()
{
  //Serial.println(" ");
  //Serial.println("triangle table");
  for (uint32_t nIndex = 0;  nIndex < WAVE_SAMPLES; ++ nIndex) 
  { 
    if( nIndex <=128 ){
      nTriangleTable[nIndex] = nIndex * 16 + 2047 ; //+offset
      //Serial.println(nTriangleTable[nIndex]);
      //Serial.println(nIndex);
    }
    else if(nIndex >128 && nIndex < 384 )
    {
      nTriangleTable[nIndex] = 4095-((nIndex-128)*16);
      //Serial.println(nTriangleTable[nIndex]);
      //Serial.println(nIndex);
    }
    else if (nIndex == 384){
      nTriangleTable[nIndex] = 0;
      //Serial.println(nTriangleTable[nIndex]);
      //Serial.println(nIndex);
    }     else if (nIndex > 384){       nTriangleTable[nIndex] = (nIndex-384)*16;        //Serial.println(nTriangleTable[nIndex]);       //Serial.println(nIndex);     }        } }
void createSq_WaveTable() {   Serial.println(" ");   Serial.println("Square Wave table");   for(uint32_t nIndex = 0;nIndex < WAVE_SAMPLES;nIndex++)   {     // despite using numbers directly here, keep in mind its related to     // WAVE_SAMPLES as a variable     // if(nIndex < (WAVE_SAMPLES/2))     if( nIndex <256 ){       nSq_WaveTable[nIndex] = 4095 ; //       Serial.println(nSq_WaveTable[nIndex]);     }     else if(nIndex >=256 && nIndex <= WAVE_SAMPLES )     {       nSq_WaveTable[nIndex] =0;       Serial.println(nSq_WaveTable[nIndex]);     }        } }

Quick-Benchmark on LUT / sine wavetable generation with DUE



During my research for my "secret" project i decided to benchmark sine wave and sine wave LOOK UP TABLE's generation, the different methods and approximations, both mathematically and methods for discrete time systems like uC's.

For research purposes, and initial development i have been actually using the Arduino Due, due to its ease of testing and debugging initial stages of ideas , for which the DAC helps a lot.
I been guessing already some limitations speed performance (considering what i want to achieve) in later stages, but for now it has been a brilliant tool.

As the ARM in the DUE was a new thing to me, and to shorten the time, i had to look around for some initial guidance regarding the registers/tmers and interrupts in order to get started.
In that sense Duane B.'s work and Groovuino's with their QUICK 'N' DIRTY synth were invaluable.
At the moment, im quite advanced, and it came to mind to use some "live" sine calculations for some other purposes other than the Pure-tone sinewave itself ( complex sinusoids and subsequent modulation, etc).
So  decided to benchmark both thei sinewavetable generation and a somewhat adapted version i used previously.
And using the millis() in Arduino, there was almost a halving of time taken to generate 512 samples of wavetable.
Duane's version took 27/28 Ms contrasting with 16/17 Ms.
Now, while this is not relevant for their synths, it is to me. Specially when im trying to squeeze as many cycles as i can already with the arduino Due, due to all the layers that the "easy way" places in between, massively contributing to the decrease in performance of speed/time.  :)
Its easy to see where the optimization is, slightly reducing the cycles needed !
Some surprises soon, and some more on this as well...

 Table_1 test code

#define WAVE_SAMPLES 512
long previousMillis = 0; 
// default int is 32 bit, in most cases its best to use uint32_t but for large arrays its better to use smaller
// data types if possible, here we are storing 12 bit samples in 16 bit ints
#define offset 2047 // In this case is the same as the Amplitude
uint16_t sin_data[WAVE_SAMPLES];
float w ;    // ψ
float yi ;
float phase;
int sign_samp;
int i;

void create2nd_sine (){
  // Serial.println(" ");
  // Serial.println("Sine table2");
  w=(2.0 * PI)/WAVE_SAMPLES;
  for (i = 0; i <= 511; i++)
  {
    yi= offset*sin(phase); // Offset is the same as the Amplitude
    phase=phase+w;
    sign_samp=offset+yi;     // dc offset translated for a 12 bit DAC
    sin_data[i]=sign_samp; // write value into array
    // Serial.println(i);
    // Serial.println(sin_data[i]);
  }
}
//

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);

}

void loop() {
  // put your main code here, to run repeatedly: 
  unsigned int result;
  unsigned long currentMillis = millis();
  create2nd_sine ();
  result=currentMillis - previousMillis;
  previousMillis = currentMillis;
  Serial.println(result);
}


 Table_2 test code


// Duane's
#define WAVE_SAMPLES 512
// default int is 32 bit, in most cases its best to use uint32_t but for large arrays its better to use smaller
// data types if possible, here we are storing 12 bit samples in 16 bit ints
uint16_t nSineTable[WAVE_SAMPLES];
long previousMillis = 0;  

void createSineTable()
{
  //   Serial.println(" ");
  //   Serial.println("Sine table");
  for(uint32_t nIndex = 0;nIndex < WAVE_SAMPLES;nIndex++)
  {
    // normalised to 12 bit range 0-4095
    nSineTable[nIndex] = (uint16_t)  (((1+sin(((2.0*PI)/WAVE_SAMPLES)*nIndex))*4095.0)/2);
    //  Serial.println(nIndex);
    //  Serial.println(nSineTable[nIndex]);
  }
}
//

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly: 
  unsigned int result;
  unsigned long currentMillis = millis();
  createSineTable();
  result=currentMillis - previousMillis;
  previousMillis = currentMillis;
  Serial.println(result);
}





For a more detailed explanation of a sinewave generator, and a few diff methods, check below link
(1) http://dubworks.blogspot.co.uk/p/blog-page.html

Tuesday, 10 September 2013

Cryptography and primes


Cryptography and primes come across, as two of my interests...
Im thinking about putting some basic codes as templates together as exercises... Maybe even do some basic RSA, eventually ?!
For now, some links

http://books.google.co.uk/books/about/In_Code.html?id=kyO7QgAACAAJ

Friday, 6 September 2013

PRIME Prime





I am amazed i didnt noticed this before.
Regards the bounded gap of prime numbers and  twin prime conjecture, a subject much loved by the great Erdős.
For hundreds of years, mathematicians have speculated that there are infinitely many twin prime pairs. In 1849, French mathematician Alphonse de Polignac extended this conjecture to the idea that there should be infinitely many prime pairs for any possible finite gap, not just 2.
In April this year, a lecturer at the University of New Hampshire named Yitang Zhang surprised everyone when his new paper arrived in the inbox of Annals of Mathematics, a prominent journal.
With it, Zhang has broken through this barrier. His paper shows that there is some number N smaller than 70 million such that there are infinitely many pairs of primes that differ by N. No matter how far you go into the deserts of the truly gargantuan prime numbers — no matter how sparse the primes become — you will keep finding prime pairs that differ by less than 70 million.
Terence Tao, Fields medal in 2006,  has proposed a joint collaboration in the polymath project to lower that number,

Sunday, 1 September 2013

Simple sine wave generator template in C


As i only used a limited amplitude on the sine wave generator for Arduino Due's DAC, im posting a template here that should help you make the necessary changes( someone asked me this).
This specific template code was written for C code in Codeblocks for Gcc, so you will have to be able to know the differences.

# include < stdio.h >
# include < stdlib.h >
# include < math.h >
# define n_points 32 //256 is ideal for microcontrollers or highers if youre computing complex sinusoids
int main ()
{
    float pi = 3.141592;
    float w ;    // ψ
    float yi ;
    float phase;
    int sign_samp;
    int sin_data[n_points];  // sine LUT Array
    int i;
    w= 2*pi;
    w= w/n_points;
    for (i = 0; i <= n_points; i++)
    {
        yi= 2047*sin(phase);
        phase=phase+w;
        sign_samp=2047+yi;     // dc offset translated for a 12 bit DAC
        //sign_samp+= b;         // Add adc value; Keep it at zero for pure sine
        sin_data[i]=sign_samp; // write value into array
        /*
        */
    }
    for (i = 0; i <= n_points; i++)
    {
        int k=sin_data[i];
        printf ("sine is %d\n", k);
        printf ("i is ... %d\n", i);
    }
    float x;
    printf ("Enter a number ... \n");
    scanf ("%f", &x); // keeps the debugging console on codeblocks open ;)
    return 0;
}





Sine plot with result of a 32 n_points as above using GNUmeric



Pseudo-code


"Two random variables were talking in a bar. They thought they were being discrete but I heard their chatter continuously "

(1) Signal Processing for Communications by Paolo Prandoni and Martin Vetterli
(2) http://dubworks.blogspot.co.uk/p/blog-page.html

Thursday, 29 August 2013

An afternoon with Leonhard Euler - Some insight into the man

i thought aout doing a short article on Euler, but then i found this video from the philoctetes Institute, with  Dominic Balestra, Loren Graham, Edward Nelson, Rebecca Newberger Goldstein, and Max Tegmark.
I think that this video does a better job than i would, plus it is a wicked lecture on Euler, easy to digest even if you don't have a maths background.
We should keep in mind that not only he was one of the most prolific contributor to maths and other areas like physics,  mechanics, fluid dynamics, optics, and astronomy., but also the one who has more terms named after him ( an overwhelming advantage, when compared to other big names in science if i might say).
In one of my previous posts, Euler's identity is mentioned, in order to achieve the sine wave generator!




http://en.wikipedia.org/wiki/Leonhard_Euler

Tuesday, 27 August 2013

Mathematical curiosities: Gödel's ontological proof of the existence of God



As a curiosity, i had to share this !!

Famous logician, mathematician, and philosopher Kurt F. Gödel was considered with Aristotle and Frege to be one of the most significant logicians in human history, Gödel made an immense impact upon scientific and philosophical thinking in the 20 th century, a time when others were pioneering the use of logic and set theory to understand the foundations of mathematics.
Calling Godel interesting is an understatement. A man who was Einstein's only reason to go to the university, in his later years; just to have the privilege of walking back home with Godel !

He used Leibniz "positive and negative properties" concept to formulate an "ontological proof" for the existence of God

Definition 1: x is God-like if and only if x has as essential properties those and only those properties which are positive

Definition 2: A is an essence of x if and only if for every property B, x has B necessarily if and only if A entails B

Definition 3: x necessarily exists if and only if every essence of x is necessarily exemplified

Axiom 1: Any property entailed by—i.e., strictly implied by—a positive property is positive
Axiom 2: If a property is positive, then its negation is not positive
Axiom 3: The property of being God-like is positive
Axiom 4: If a property is positive, then it is necessarily positive
Axiom 5: Necessary existence is a positive property
Axiom 6: For any property P, if P is positive, then being necessarily P is positive

Axiom 1 assumes that it is possible to single out positive properties from among all properties. Gödel comments that "Positive means positive in the moral aesthetic sense (independently of the accidental structure of the world)... It may also mean pure attribution as opposed to privation (or containing privation)." (Gödel 1995). Axioms 2, 3 and 4 can be summarized by saying that positive properties form a principal ultrafilter.
From these axioms and definitions and a few other axioms from modal logic, the following theorems can be proved:

Theorem 1: If a property is positive, then it is consistent, i.e., possibly exemplified.
Corollary 1: The property of being God-like is consistent.
Theorem 2: If something is God-like, then the property of being God-like is an essence of that thing.
Theorem 3: Necessarily, the property of being God-like is exemplified.


Thursday, 11 April 2013