8.10 Sum of series Write a program to calculate and display the sum of the series:

1 - 1/2 + 1/3 - 1/4 + ...

Until a term is reached that is less than 0.0001


I do not need help with the code! What comes next in the series? Is there a formula for this?

It's been far too long since I took math!!!

Thanks in advance

the next number would be 1/5, then 1/6, then 1/7, and so on. The denominator increases by 1.

In my opinion the best way to tackle this is with a recursive algorithm. This equation looks kind of like a Fibonacci's numbers problem with a slight difference.

the equation should be X = X - (1 / (n+1)) + (1 / (n+2)) where x and n both start as 1

if you need help setting up the algorithm make another post

Is there a simple way to change a positive number to a negative number???

float d = 1.0f; How can I flip d between pos. and neg.?

Thanks in advance

Is there a simple way to change a positive number to a negative number???

float d = 1.0f; How can I flip d between pos. and neg.?

Thanks in advance

if (d > 0)
{
        d = -(d);
}
else if (d < 0)
{
      d = Math.abs(d);
}

Of course this would work for both:

d = -(d);
that would make positive values negative and negative values positive.

So for the above homework question, the following should be fine?

import java.awt.*;
import java.applet.*;

public class Ch8_10 extends Applet
{
	private float d = 2.0f, sum = 1.0f, term = 0.0f;	
	  
	public void paint(Graphics g)
	{
	
		do	
		{
			term = 1/d;
			sum = sum - term;		
			d++;
			sum = -(sum);		
		
		}
		while(term > 0.0001);		
		
		
		g.drawString("Sum = "+ sum,20,20);
		g.drawString("Term = " + term, 20, 40);
		g.drawString("Denominator = " + d, 20, 60);
	}
}

Output:

Sum = -0.6930917
Term = 1.0E-4
Denominator = 10001.0


Are there better ways to do this? I wanted to make it work before I asked.

Thanks for the help

Jay

change this

private float d = 2.0f, sum = 1.0f, term = 0.0f;

It's very bad practice to declare multiple variables on a single line, never do it!

change this

private float d = 2.0f, sum = 1.0f, term = 0.0f;

It's very bad practice to declare multiple variables on a single line, never do it!

Actually you can't declare floats with decimall places can you? You have to add d a 'd' at the end to symbolize a double.

no, you can. Unless you specify the f at the end it defaults to a double though (causing a compiler error).

float is a single precision floating point number, double a double precision floating point number.

no, you can. Unless you specify the f at the end it defaults to a double though (causing a compiler error).

float is a single precision floating point number, double a double precision floating point number.

K, I knew I was going wrong somewhere.

This article has been dead for over six months. Start a new discussion instead.