0

I am frankly a novice to Java. I have a project that i am working on where I want to find a way to create a polynomial function based on a sequence of numbers.

Anyway, my question is that i have created an array that has stored a sequence. I would like to now find the difference between the elements. So for example. i want to find this calculation a[2] - a[1] and then store accordingly into another array.

What i have already done is this. I am not too confident about this but mostly am having a problem storing each into another array. I am sure this is a bit of a stupid question however, I would appreciate any help possible.

for(int i = 0;i<=sequence.length;i++){
    double diff = sequence[i+1]- sequence[i];
}

2 Answers 2

4

Assuming sequence is an array of doubles, try this:

double[] diffs = new double[sequence.length - 1];
for (int i = 0; i < sequence.length - 1; i++) {
    diffs[i] = sequence[i + 1] - sequence[i];
}
Sign up to request clarification or add additional context in comments.

3 Comments

@Ray It will work. Length = 10, i = 8 will be the last to be used.
Oh. this is awesome. I can't believe i didn't think of this. thankyou so much guys . You are fantastic. Thankyou very much, Just got me out of a jam,
yeah. i don't really know how to. but as soon as i find out. i definitely will.
2
arr = new int[sequence.length - 1];
// length will be smaller by 1 than the original sequence

for(int i = 0; i < sequence.length - 1; i++){
   arr[i] = sequence[i+1]- sequence[i]; // no point making it double 
   //if both elements are ints, they won't have decimals to use in calculation.
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.