How do you write a summation program for 1/n

nonxcarbonx

Distinguished
Jun 6, 2009
36
0
18,580
I want to run it's summations from 1 to an incredibly large number (as a matter of curiosity) but unfortunately to this point I've only got knowledge about hardware and not programing. How do you go about writing a program that can compute that to say,1 to 10,000,000 via the summation of 1/n (takes a long time on my ti 89 :pt1cable: )

As I said, I've never written code before and I don't know how to run it, but could someone explain? It seems like this one would likely be simple, but I don't know. Thanks.
 

randomizer

Distinguished
Well what language do you want to use? This is important because some languages (like the one below) will only run on Windows.

Let me make sure I understand exactly what you want to do. 1/1 + 1/2 + 1/3 + 1/4 etc?

If I was going to do it in C# .NET, I'd do something like this:

Code:
int sum = 0;
for (int n = 1; n <= 10000000; n++)
{
      sum = sum + 1/n;
}
Console.Write(sum);

Ignore the line numbers, the forum adds those. There's a bit extra code around that which applies to alost every program run in the console but the code here is the important stuff. If you use Visual Studio the rest is pretty much auto-generated anyway. Different languages will do things differently.

Basically what this code does is declare an integer called "sum" and assign it a value of 0, then it does a loop that starts off by declaring an integer called "n." The loop runs the segment of code inside the braces which adds the value of sum and 1/n together and stores that value back into the memory location where sum is, replacing the original. The loop then tests to see if n is less than or equal to 10,000,000 and if it is it increments n by 1 (n++) and runs the code in the middle again. Once the n <= 10000000 statement is false the loop exits and prints the value of sum to the console window.
 

nonxcarbonx

Distinguished
Jun 6, 2009
36
0
18,580
I downloaded visual studio but I tried to start a new project and I couldn't figure out how to do this. I copied and pasted but it came up with a bunch of errors. How do I set it up?
 

randomizer

Distinguished
Assuming you want to use the above code, create a new Project using Visual C# and make sure you pick Console not Windows program. Copy the above code inside the braces for the section called Main. Don't delete the code that is generated for you. It should look roughly like this:

Code:
public static void Main(string args[])
{
     int sum = 0;
     for (int n = 1; n <= 10000000; n++)

     {
           sum = sum + 1/n;
     }

     Console.Write(sum);
}

Then compile it. If you get errors, tell me what they are. I haven't done programming for a while and might have forgotten something simple. Make sure you don't copy the line numbers from above.
 

nonxcarbonx

Distinguished
Jun 6, 2009
36
0
18,580
It looks like this:

Module Module1

public static void Main(string args[])
{
int sum = 0;
for (int n = 1; n <= 10000000; n++)

{
sum = sum + 1/n;
}

Console.write(sum);
}
End Sub

End Module

And it came up with these:
Error 1 'Sub Main' was not found in 'ConsoleApplication1.Module1'. ConsoleApplication1
Error 2 'Static' is not valid on a member variable declaration. 3 12 ConsoleApplication1
Error 3 End of statement expected. 3 24 ConsoleApplication1
Error 4 Syntax error. 4 5 ConsoleApplication1
Error 5 Declaration expected. 5 9 ConsoleApplication1
Error 6 Statement cannot appear outside of a method body. 6 9 ConsoleApplication1
Error 7 Syntax error. 8 9 ConsoleApplication1
Error 8 Declaration expected. 9 13 ConsoleApplication1
Error 9 Syntax error. 10 9 ConsoleApplication1
Error 10 Declaration expected. 12 9 ConsoleApplication1
Error 11 Syntax error. 13 5 ConsoleApplication1
Error 12 'End Sub' must be preceded by a matching 'Sub'. 14 5 ConsoleApplication1

Edit: I noticed that when I post the site edits the spacings. They're the same as you wrote, but with module module 1 at the far left and everything indented 1 tab or two tabs except for end module.
 

randomizer

Distinguished
You need to use [ code][ /code] tags (without the spaces inside) for it to be formatted the way mine was, keeping indentations. I see your problem, you're pasting C# code into a Visual Basic project. You need to make sure that you select Visual C# when creating a new project. You may have to expand "Other Languages" to find it if it's not the default language.
 

mindless728

Distinguished
Jul 15, 2008
130
0
18,660
oh ok, at least you know you won't get a number that is worth anything

while you are at it make it multi threaded to go faster

so you can not hit convergence faster
 

randomizer

Distinguished
Here's a program for you that does this but allows you to enter any number for n. It's very crude, not well optimised and I hacked it together in a short period of time so don't expect perfect programming techniques. :) It does work though. It's also not multithreaded so expect it to take a while if you're doing a large number. You should just be able to replace the entire code with this as long as it's a C# project.

Code:
using System;
using System.Collections.Generic;
using System.Text;

namespace Sum1OverN
{
    class Program
    {
        public static void Main(string[] args)
        {
            bool calc = true;

            while (calc)
            {
                Console.Clear();
                decimal sum = 0;
                decimal n = 0;
                int numDecPlaces = 2;
                bool valid = false;

                Console.Write("Please enter a value for n: ");

                while (!valid)
                {
                    try
                    {
                        n = Convert.ToDecimal(Console.ReadLine());
                        valid = true;
                    }
                    catch
                    {
                        Console.Write("That was not a number, try again: ");
                    }
                }

                Console.Write("\nPlease enter the number of decimal places to round to: ");

                valid = false;
                while (!valid)
                {
                    try
                    {
                        numDecPlaces = Convert.ToInt32(Console.ReadLine());
                        valid = true;
                    }
                    catch
                    {
                        Console.Write("That was not a number, try again: ");
                    }
                }

                Console.WriteLine("\nCalculating now, this might take a while...");

                for (decimal i = 1; i <= n; i++)
                {
                    sum = sum + (1 / i);

                    if (i == n / 2 && n >= 5000000)
                    {
                        Console.WriteLine("\nHalf way there...");
                    }
                }
                Console.Write("\nThe final sum is ");
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.Write("{0:n" + numDecPlaces + "} \n", sum);
                Console.ForegroundColor = ConsoleColor.Gray;

                valid = false;

                while (!valid)
                {
                    Console.Write("Recalculate (y/n)? ");
                    char input = Console.ReadKey().KeyChar;
                    switch (input)
                    {
                        case 'y':
                            calc = true;
                            valid = true;
                            break;
                        case 'n':
                            calc = false;
                            valid = true;
                            break;
                        default:
                            break;
                    }
                }
            }
        }
    }
}
 

randomizer

Distinguished
I don't know how to do multithreading at all. It's something that I've been planning to learn but haven't :) University only teaches you the basics. Although I can do more than most of the people who were in my class because I've done some programming outside of the pointless console programs they made us do. Programming with a goal is much easier than just programming.
 

nonxcarbonx

Distinguished
Jun 6, 2009
36
0
18,580
Where do i write that in here?
Module Module1

Sub Main()

End Sub

End Module
I'm guessing between sub main and end sub. Then how do I get it to run? I'm using visual basic, but is there another program i should/could be using (for free)?

P.S. I recognize I'm pretty ignorant about programming now, but soon I'll take a class so I can write my own :wahoo:
 

randomizer

Distinguished
Visual Basic is another language. You need Visual C# for the above code. Did you download the Express version of VS? If so, you need this: http://www.microsoft.com/express/vcsharp/

Otherwise you can, if you get access to it, get Visual Studio 2008 Professional which has all .NET languages (provided you installed them).

Once you've got a Visaul C# project running you can delete all of the code it generates for you and paste in the above in it's place. Remove the line numbers though.

I can try and re-write the above in Visual Basic but I'm not as good at it and honestly, I hate VB :lol:
 

mindless728

Distinguished
Jul 15, 2008
130
0
18,660
i hate VB as well

@randomizer, multithreading isn't too bad, i taught myself how to do it about a year and a half ago, im only a 3rd year Comp Sci student

the opengl code i did was much harder, so are sockets (i made a connection class for the sockets so i don't have to worry about the underlying code all of the time)

and yes i get very bored in my CS classes
 

randomizer

Distinguished
It's alot easier with .NET. I managed to spawn two threads within 20 minutes of reading online. Unfortunately my program logic isn't quite right so it doesn't work right :p
 

randomizer

Distinguished
Got it. Two threads do half of the work each (1-50,000,000; 50,000,001-100,000,000; where n = 100,000,000). Oddly it seems the .NET Common Language Runtime assumes one spawned thread should use two logical cores where Hyperthreading is in use (unless the Windows 7 scheduler was responsible for that). The singlethreaded version loaded 2 logical cores to about 40-50% each, while the multithreaded version had two spawned threads but used 4 logical cores with varying loads.

Sum1OverN.png
 

mindless728

Distinguished
Jul 15, 2008
130
0
18,660
idk, i think CreateThread() (c/c++) is easy to use as well, just have to remember windows.h

btw, M$ msdn library is quite handy, its where i learned how to use the winapi, multi threading, sockets

btw nice job on the multi threading
 

randomizer

Distinguished
It's actually pretty bad. I don't know how to make the main program wait until the threads are done before continuing on (this is where an event-based Windows Form program would be easier) so I just put a while loop in that checks if all the threads are stopped. If not, it just keeps checking. Sucks up quite a few CPU cycles I'd assume. Also, the check to see if a worker is "half way there" adds about 10 seconds to the computation time :lol:
 

mindless728

Distinguished
Jul 15, 2008
130
0
18,660
well, thats happens, though in c++ doing this out to n=100,000,000 only takes about 2s or so with a single thread

though in c++ i do a while with a sleep to wait for threads

Code:
while(there are still threads computing)
     Sleep(10); //sleeps for 10ms
}