Sine Wave Music generator [closed] - audio

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I've been doing research on trying to understand the way sounds and sine waves work, particularly with chords. So far, my understanding is as follows:
1) b(t) = sin(Api(t)) is the base note of the chord at frequency A.
2) T(t) = sin(5/4piA(t)) is the major third of the base b(t).
3) D(t) = sin(3/2piA(t)) is the dominant (fifth) of the base b(t).
4) A(t) = sin(2Api(t)) is the octave.
Each one alone is a separate frequency which is easy for a computer generator to sound. However, the major chord of the note with frequency A is as follows:
Major Chord = b+T+D+A
I was wondering if anyone has a way to make a computer synthesizer play this function so I can hear the result; most programs I have found only take Hz as an input, an while this function has a wavelength, it's different from the simple sine wave with the same wavelength.
Note: will post this in the physics and music sections as well - just wondering if you computer scientists know something about this.

You just need to scale the function so that the root of the chord is at the desired frequency. For example, the root frequency of the A in an A major chord is at 440Hz. Therefore the 3rd, 5th and octave would be at 440*5/4, 440*3/2 and 440*2, respectively.
To generate the sounds on the computer, the first thing your going to need to do is convert the functions from continuous time to discrete time and from continuous level to a quantized level. There are a lot of good references on the internet about this topic.
The continuous time version of a sine wave would be something like
y = ampl * sin(2 * pi * freq)
The discrete time version would like this:
y[n] = ampl * sin(2 * pi * freq / sampleRate)
where n is a sample number and sampleRate is the number of divisions of a second.
Then components of the major chord would be constructed in the following manner:
root[n] = ampl * sin(2 * pi * freq / sampleRate)
third[n] = ampl * sin(2 * pi * freq * (5/4) / sampleRate)
fifth[n] = ampl * sin(2 * pi * freq * (3/2) / sampleRate)
octave[n] = ampl * sin(2 * pi * freq * 2 / sampleRate)

Related

Linear decay as learning rate scheduler (pytorch)

I have read about LinearLR and ConstantLR in the Pytorch docs but I can't figure out, how to get a linear decay of my learning rate. Say I have epochs = 10 and lr=0.1 then I want to linearly reduce my learning-rate from 0.1 to 0 (or any other number) in 10 steps i.e by 0.01 in each step.
The two constraints you have are: lr(step=0)=0.1 and lr(step=10)=0. So naturally, lr(step) = -0.1*step/10 + 0.1 = 0.1*(1 - step/10).
This is known as the polynomial learning rate scheduler. Its general form is:
def polynomial(base_lr, iter, max_iter, power):
return base_lr * ((1 - float(iter) / max_iter) ** power)
Which in your case would be called with polynomial(base_lr=0.1, max_iter=10, power=1).

Divide by a number which is not power of 2 in Verilog RTL coding

For multiplication and division, we can use the left and right shifts.
x>>2 // it will right shift by 2. ---> 2^2=4. (Multiply by 4 or divide by 4, depends on MSB/LSB)
However, if we want to divide by a number that isn't the power of 2, how can we achieve the required purpose?
Booth's algorithm is an additive one and can take a comparatively longer time than the multiplicative algorithms, like the Newton-Raphson algorithms found in this educational PDF.
Each next approximation is calculated using the previous approximation.
X(N+1) = X(N)(2 - b * X(N)), where x(0)=1
So, to find the inverse of b, i.e. 1/b, where b=0.6 (error=e(x)), it takes about 5 iterations.
X(000) = 1.000
X(001) = 1.000 * (2 - (1.000 * 0.6)) = 1.400
X(002) = 1.400 * (2 - (1.400 * 0.6)) = 1.624
X(003) = 1.624 * (2 - (1.624 * 0.6)) = 1.6655744
X(004) = X(003) * (2 - (X(003) * 0.6)) = 1.666665951
X(005) = X(004) * (2 - (X(004) * 0.6)) = 1.666666668
which approximates the answer, which is 1.6666666667.
I included this example in case the referenced PDF disappears. See the referenced PDF or look up the Newton-Raphson algorithm for more information.
By using Booth's restoring division algorithm

Shading with squared falloff always makes everything black

I have recently tried to change the current way I calculate diffuse lighting in my RayTracer. It used to be calculated like this:
float lambert = (light_ray_dir * normal) * coef;
red += lambert * current.color.red * mat.kd.red;
green += lambert * current.color.green * mat.kd.green;
blue += lambert * current.color.blue * mat.kd.blue;
where coef is an attenuation coefficient that starts at 1 for each pixel and is then attenuated for each reflected ray that is generated by this line:
coef *= mat.reflection;
This worked well.
But I decided to try something more realistic and implemented this:
float squared_attenuation = LIGHT_FALLOFF * lenght;
light_intensity.setX ((current.color.red /*INTENSITY*/)/ squared_attenuation);
light_intensity.setY ((current.color.green /*INTENSITY*/)/ squared_attenuation);
light_intensity.setZ ((current.color.blue /*INTENSITY*/)/ squared_attenuation);
red += ALBEDO * light_intensity.getX() * lambert * mat.kd.red;
green += ALBEDO * light_intensity.getY() * lambert * mat.kd.green;
blue += ALBEDO * light_intensity.getZ() * lambert * mat.kd.blue;
where LIGHT_FALLOFF it is a constant value:
#define LIGHT_FALLOFF M_PI * 4
and length it is the length of the vector that goes from the point light center to the intersect point:
inline float normalize_return_lenght () {
float lenght = sqrtf (x*x + y*y + z*z);
float inv_length = 1/lenght;
x = x * inv_length, y = y * inv_length, z = z * inv_length;
return lenght;
}
float lenght = light_ray_dir.normalize_return_lenght ();
The problem is that all this is generating nothing more than a black screen! The main culprit is the length that goes as the divisor in the light_intensity.set. It makes the final color values being some value ^ -5. However, even if I replace it by one (ruining my goal of a realistic light attenuation), I still get color values to close to zero still, hence a black image.
I tried to add another light_sources closer to the objects, however the fact that the models that shall be shaded are made of multiple polygons with different coordinates, make hard to determine a goodl ocation for them.
So I ask. It seems normal to you that this is happening or it seems a bug? For me theory, does not seems strange for me, since the attenuation is quadratic.
Is does not seem, there is a some hint as to where to place the light sources, or to anything as can get an image that is not all black?
Thanks for reading all this!
P.S: Intensity is commented out because on the example that I used to do my code, it was one
So you are assuming that the light has a luminosity of "1" ?
How far away is your light?
If your light is - say - 10 units away, then they contribution from the light will be 1/10, or a very small number. This is probably why your image is dark.
You need to have quite large numbers for your light intensity if you are going to do this. In one of my scenes, I have a light that is about 1000 units away (pretending to be the Sun) and the intensity is 380000!!
Another thing ... to simulate reality, you should be using 1 / length^2. The light intensity falls off with the square of distance, not just with distance.
Good luck!

Numerical differentiation using Cauchy (CIF)

I am trying to create a module with a mathematical class for Taylor series, to have it easily accessible for other projects. Hence I wish to optimize it as far as I can.
For those who are not too familiar with Taylor series, it will be a necessity to be able to differentiate a function in a point many times. Given that the normal definition of the mathematical derivative of a function will require immense precision for higher order derivatives, I've decided to use Cauchy's integral formula instead. With a little bit of work, I've managed to rearrange the formula a little bit, as you can see on this picture: Rearranged formula. This provided me with much more accurate results on higher order derivatives than the traditional definition of the derivative. Here is the function i am currently using to differentiate a function in a point:
def myDerivative(f, x, dTheta, degree):
riemannSum = 0
theta = 0
while theta < 2*np.pi:
functionArgument = np.complex128(x + np.exp(1j*theta))
secondFactor = np.complex128(np.exp(-1j * degree * theta))
riemannSum += f(functionArgument) * secondFactor * dTheta
theta += dTheta
return factorial(degree)/(2*np.pi) * riemannSum.real
I've tested this function in my main function with a carefully thought out mathematical function which I know the derivatives of, namely f(x) = sin(x).
def main():
print(myDerivative(f, 0, 2*np.pi/(4*4096), 16))
pass
These derivatives seems to freak out at around the derivative of degree 16. I've also tried to play around with dTheta, but with no luck. I would like to have higher orders as well, but I fear I've run into some kind of machine precission.
My question is in it's simplest form: What can I do to improve this function in order to get higher order of my derivatives?
I seem to have come up with a solution to the problem. I did this by rearranging Cauchy's integral formula in a different way, by exploiting that the initial contour integral can be an arbitrarily large circle around the point of differentiation. Be aware that it is very important that the function is analytic in the complex plane for this to be valid.
New formula
Also this gives a new function for differentiation:
def myDerivative(f, x, dTheta, degree, contourRadius):
riemannSum = 0
theta = 0
while theta < 2*np.pi:
functionArgument = np.complex128(x + contourRadius*np.exp(1j*theta))
secondFactor = (1/contourRadius)**degree*np.complex128(np.exp(-1j * degree * theta))
riemannSum += f(functionArgument) * secondFactor * dTheta
theta += dTheta
return factorial(degree) * riemannSum.real / (2*np.pi)
This gives me a very accurate differentiation of high orders. For instance I am able to differentiate f(x)=e^x 50 times without a problem.
Well, since you are working with a discrete approximation of the derivative (via dTheta), sooner or later you must run into trouble. I'm surprised you were able to get at least 15 accurate derivatives -- good work! But to get derivatives of all orders, either you have to put a limit on what you're willing to accept and say it's good enough, or else compute the derivatives symbolically. Take a look at Sympy for that. Sympy probably has some functions for computing Taylor series too.

Calculate distance between two points in bing maps

Ihave a bing map, and a two points :
Point1,Point2 and i want to calculate the distance between these two points? is that possible?
and if i want to put a circle on the two third of the path between point1 and point2 and near point2 ...how can i make it?
Microsoft has a GeoCoordinate.GetDistanceTo Method, which uses the Haversine formula.
For me other implementation return NaN for distances that are too small. I haven't run into any issues with the built in function yet.
See Haversine or even better the Vincenty formula how to solve this problem.
The following code uses haversines way to get the distance:
public double GetDistanceBetweenPoints(double lat1, double long1, double lat2, double long2)
{
double distance = 0;
double dLat = (lat2 - lat1) / 180* Math.PI;
double dLong = (long2 - long1) / 180 * Math.PI;
double a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2)
+ Math.Cos(lat1 / 180* Math.PI) * Math.Cos(lat2 / 180* Math.PI)
* Math.Sin(dLong/2) * Math.Sin(dLong/2);
double c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));
//Calculate radius of earth
// For this you can assume any of the two points.
double radiusE = 6378135; // Equatorial radius, in metres
double radiusP = 6356750; // Polar Radius
//Numerator part of function
double nr = Math.Pow(radiusE * radiusP * Math.Cos(lat1 / 180 * Math.PI), 2);
//Denominator part of the function
double dr = Math.Pow(radiusE * Math.Cos(lat1 / 180 * Math.PI), 2)
+ Math.Pow(radiusP * Math.Sin(lat1 / 180 * Math.PI), 2);
double radius = Math.Sqrt(nr / dr);
//Calculate distance in meters.
distance = radius * c;
return distance; // distance in meters
}
You can find a good site with infos here.
You can use a geographic library for (re-)projection and calculation operations if you need more accurate results or want to do some math operations (e.g. transform a circle onto a sperioid/projection). Take a look at DotSpatial or SharpMap and the samples/unittests/sources there... this might help to solve your problem.
Anyway if you know the geodesic distance and bearing you can also calculate where resulting target position (center of your circle) is, e.g. see "Direct Problem" of Vincenty's algorithms. Here are also some useful algorithm implementations for silverlight/.net
You might also consider to post your questions at GIS Stackexchange. They discuss GIS related problems like yours. Take a look at the question for calculating lat long x-miles from point (as you already know the whole distance now) or see the discussion here about distance calculations. This question is related to the problem how to draw a point on a line in a given distance and is nearly the same (cause you need a center and radius).
Another option is to use ArcGIS API for Silverlight which can also display Bing Maps. It is open source and you can learn the things you need there (or just use them, cause they already exists in the SDK). See the Utilities examples tab within the samples.
As I already mentioned: Take a look at this page to get more infos regarding your problem. There you'll find a formula, Javascript code and an Excel sample for calculating a destination point by a given distance and bearing from start point (see headlines there).
It shouldn't be difficult to "transform" the code to your c#-world.

Resources