19
Week 7 - Wednesday

Week 7 -Wednesday

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

Week 7 - Wednesday

What did we talk about last time? Sound

Everything you'd want to do with sound:

To do interesting things, you have to manipulate the array of samples

Make sure you added StdAudio.java to your project before trying to use it

Method Use

double[] read(String file) Read a WAV file into an array of doubles

void save(String file, double[] input) Save an array of doubles (samples) into a WAV file

void play(String file) Play a WAV file

void play(double[] input) Play an array of doubles (samples)

What if we wanted to play the second half of a sound followed by the first half? I know, why would we want to do that?

double[] samples = StdAudio.read(file);double[] switched = new double[samples.length];

for (int i = 0; i < samples.length/2; ++i)switched[i + samples.length/2] = samples[i];

for (int i = samples.length/2; i < samples.length; ++i)switched[i - samples.length/2] = samples[i];

StdAudio.play(switched);

When you declare an array, you are only creating a variable that can hold an array

To use it, you have to create an array, supplying a specific size:

This code creates an array of 100 ints

int[] list = new int[100];

You can access an element of an array by indexing into it, using square brackets and a number

Once you have indexed into an array, that variable behaves exactly like any other variable of that type

You can read values from it and store values into it Indexing starts at 0 and stops at 1 less than the length

list[9] = 142;System.out.println(list[9]);

When you instantiate an array, you specify the length Sometimes (like in the case of args) you are given an array of

unknown length You can use its length member to find out

int[] list = new int[42];int size = list.length;// Prints 42System.out.println("List has " + size + " elements");

Recently, we showed you how to add a set of numbers together as they were input by a user

Although this is a useful technique, not every operation is possible

We can find the sum or the average of the numbers because we only need to see the numbers once

What operation needs to see the numbers more than once?

Variance is a measurement of how spread out numbers are from their mean

One way to calculate it requires that we find the mean first The formula is:

Where N is the number of elements, xi is the ith element, and �x is the mean

∑=

−=N

ii xx

N 1

22 )(1σ

Given an array of doubles called numbers, here's the code for finding their variance

double average = 0;double variance = 0;

for (int i = 0; i < numbers.length; ++i)average += numbers[i];

average /= numbers.length;

for (int i = 0; i < numbers.length; ++i) {double temp = numbers[i] – average;variance += temp*temp;

}variance /= numbers.length;

More array examples StdDraw

Keep reading Chapter 6 of the textbook Keep working on Project 3