I'm quite new to programming so this shouldn't be a problem to most of you. I'm supposed to write a program which sums 1/n^2 (n being consecutive natural numbers) while elements are bigger than constant eps=0,001. I wrote a piece of code and tried to edit it but I'm still stuck in an infinite loop in which I just get consecutive numbers, but it's quite obvious the sum should be between 1 and 2. I'd be more than grateful if anyone could show me what it is that I'm doing wrong.
namespace program
{
class Program
{
static void Main(string[] args)
{
const double eps=0.001;
int n=1;
double x;
x = 1 / (n * n);
double sum=x;
while (x > eps)
{
n++;
sum = sum + x;
Console.WriteLine(sum);
}
Console.Write("\nSum: {0}.", sum);
Console.ReadLine();
}
}
}
You never recalculate the value of x, so the while condition never becomes false. If you move the assignment inside, your code won't loop forever.
const double eps=0.001;
int n=1;
double x;
double sum=x;
while (true)
{
x = 1.0 / (n * n);
if (x < eps) {
break;
}
n++;
sum = sum + x;
Console.WriteLine(sum);
}
Console.Write("\nSum: {0}.", sum);
Console.ReadLine();
A couple of things. First of all
1 / (n * n)
is an integer expression and is always either 0 or 1. You need to make it a floating point expression like this:
1.0 / (n * n)
And then you need to update x inside the loop rather than assigning to x once and once only.
Perhaps like this:
static void Main(string[] args)
{
const double eps = 0.001;
int n = 1;
double x = 1.0 / (n * n);
double sum = 0.0;
while (x > eps)
{
sum += x;
n++;
x = 1.0 / (n*n);
Console.WriteLine(sum);
};
Console.Write("\nSum: {0}", sum);
Console.ReadLine();
}
The downside of this is that the expression for x is written twice. So a better way is like this:
static void Main(string[] args)
{
const double eps = 0.001;
int n = 1;
double sum = 0.0;
while (true)
{
double x = 1.0 / (n * n);
if (x <= eps)
break;
sum += x;
n++;
Console.WriteLine(sum);
};
Console.Write("\nSum: {0}", sum);
Console.ReadLine();
}
Related
Calculate the following sum
1!/1 + 2!/(1+1/2) + 3!/(1+1/2+1/3) + ... + n!/ (1+1/2+1/3+...+1/n), where n > 0.
public static double GetSumSix(int n)
{
double i, result = 0.0;
static double factorial(double n)
{
double res = 1;
for (double i = 2; i <= n; i++)
res *= i;
return res;
}
for (i = 1.0; i <= n; i++)
{
result += factorial(i) / (1.0 / i);
}
return result;
}
Help me please , I don't understand why is my solution not working?
Your denominator logic is incorrect. You could create another function to work out what '1/1+1/2+...+1/n' is and use that in the denominator? right now your code will work out 1+2!*2+3!*3+...
You could actually use something similar to your factorial method
static double GetDenominator(double n)
{
double res = 1;
for (double i = 2; i <= n; i++)
//insert code here
return res;
}
The Lemon's answer is correct, you're not accumulating the denominator of the sequence so what you were calculating was:
f(n) = 1!/1 + 2!/(1/2) + 3!/(1/3) + ... n!/(1/n)
Since both the numerator and denominator of each term are algorithmically linked to the values in the prior term you can simply update them each pass through the loop. This is (slightly) faster and fairly easy to read.
public static double GetSumSix(int n)
{
double factorial = 1;
double denominator = 1;
double accum = 1;
for (int i = 2; i <= n; i++)
{
factorial *= i;
denominator += 1.0d/i;
accum += factorial / denominator;
}
return accum;
}
Your logic is not correct as per your question , also your code won't execute as you have a function inside your GetSumSix function. I have put some helping points in below code so you will understand how the logic works.
using System;
public class Program
{
public static void Main()
{
var Calculate = GetSumSix(3);
Console.WriteLine("The Answer is " + Calculate);
}
public static double GetSumSix(int n)
{
int i;
double result = 0.0;
int factorial = 1;
string calculatedFormula = String.Empty;
string FinalFormat = String.Empty;
//Find n!
for(int x=n;x>=1;x--)
{
factorial *= x;
}
// Find Denominator (1+1/2+1/3+…+1/n)
for (i = 1.0; i <= n; i++)
{
result += GetDenominator(i, ref calculatedFormula);
FinalFormat += calculatedFormula;
}
result = factorial/result;
Console.WriteLine("Calculated Formula is:"+ factorial +"/(" + FinalFormat +")When N is :" + n);
return result;
}
public static double GetDenominator(double n, ref string cal)
{
if (n == 1)
{
cal += n + "+ ";
return 1;
}
else
{
cal = "1/" + n + "+ ";
return 1 / n;
}
}
}
Thanks.
I need to display odds to win with ten decimals if I play with just one variant, for six five and four numbers. For example I need to have this 0.0000000715 but I have this 0.0027829314 if I introduce 49,6,I. What is the problem?How can I make it work? I am a beginner and I don't know how i can obtain this 0.0000000715.
class Program
{
static void Main(string[] args)
{
int n = Convert.ToInt32(Console.ReadLine());
int k = Convert.ToInt32(Console.ReadLine());
string category = Console.ReadLine();
switch (category)
{
case "I":
calculate(n,k);
break;
case "II":
calculate(n, k);
break;
case "III":
calculate(n, k);
break;
}
}
static void calculate(int n, int k)
{
int nk = n - k;
decimal count = prod(1, nk) / prod(k + 1, n);
decimal r = prod(1, k) / prod(n - k + 1, n);
decimal sum = count * r;
Console.WriteLine(Math.Round(r,10));
}
static decimal prod(int x, int y)
{
decimal prod = 0;
for(int i = x; i <= y; i++)
{
prod = x * y;
}
return prod;
}
}
The general solution would be bc(6,n)*bc(49-6,6-n)/bc(49, 6), where n is, 4, 5 or 6 and bc is the binomial coefficient.
Btw.: double should be enough for 10 decimal places, there is no need to use decimal.
using System;
public class Program
{
//bonomial coefficient
static double bc(double n, double k)
{
if (k == 0 || k == n)
return 1;
return bc(n - 1, k - 1) + bc(n - 1, k);
}
public static void Main()
{
for(int n = 4; n <=6; ++n){
Console.WriteLine(bc(6,n)*bc(49-6,6-n)/bc(49, 6));
}
}
}
I am not sur what function you were using.
The chances of winning all 6 numbers is 1 in 13,983,816
The actual calculation is this:
49C6 = 49!/(43! x 6!) = 13983816
So the probability to win is 1 / 13,983,816 = 0.0000000715
Your prod function should look like:
static decimal prod(int x, int y)
{
decimal prod = 1;
for(int i = x; i <= y; i++)
{
prod = prod * i;
}
return prod;
}
As jjj mentioned, you overwrite "prod" everytime, but you need to add it
I made this program to find the power of any number using recursion and it works, but also I need to find negative power of the number, for example, I have the base = 2 and the exponent = -3 so the result = 0.125,
what should I do?
public static int power(int x, int n )
{
if (n < 0)
{
Console.WriteLine("invalid");
return 0;
}
else if (n == 1)
{
return x;
}
else if (n == 0)
{
return 1;
}
else
{
return x * power(x, n - 1);
}
}
static void Main(string[] args)
{
Console.Write("enter the base: ");
int x = int.Parse(Console.ReadLine());
Console.Write("enter the power:");
int n = int.Parse(Console.ReadLine());
int z = power(x, n);
Console.WriteLine(z);
}
Since the result of raising a number to a negative power is just 1 divided by the number raised to the non-negative power, you can change you method like so (note that we also need to return a double type, since we're dealing with fractional values):
public static double power(int x, int n)
{
if (n < 0) return 1 / power(x, -n); // recursive call with '-n' for negative powers
if (n == 0) return 1;
if (n == 1) return x;
return x * power(x, n - 1);
}
Now it works with negative numbers:
public static void Main(string[] args)
{
Console.WriteLine(power(2, -3));
GetKeyFromUser("\nDone! Press any key to exit...");
}
Output
I am having trouble with my Monte Carlo Pi program calculating properly.
Basically, pi is only displaying up to 2 decimal points only at the moment, and I feel the calculation has gone wrong somewhere as the closest pi calculation as number gets higher is 2.98-3.04.
My code is pasted below.
static void Main(string[] args)
{
double n;
double count;
double c = 0.0;
double x = 0.0, y = 0.0;
double pi;
string input;
Console.WriteLine("Please input a number of dots for Monte Carlo to calculate pi.");
input = Console.ReadLine();
n = double.Parse(input);
Random rand = new Random();
for (int i = 1; i < n; i++ )
{
x = rand.Next(-1, 1);
y = rand.Next(-1, 1);
if (((x * x) + (y * y) <= 1))
c++;
pi = 4.0 * ( c / i );
Console.WriteLine("pi: {0,-10:0.00} Dots in square: {1,-15:0} Dots in circle: {2,-20:0}", pi, i, c);
}
}
These calls
x = rand.Next(-1, 1);
y = rand.Next(-1, 1);
give you an integer. But you need doubles:
x = rand.NextDouble() * 2 - 1;
y = rand.NextDouble() * 2 - 1;
The random numbers should be generated between 0 and 1 and not -1 and 1.
Used this fixed version of your code as "mysterious code" for students.
using System;
namespace mysCode
{
class Program
{
static double euclideanDistance(double x1, double y1, double x2, double y2)
{
double dX = x2 - x1;
double dY = y2 - y1;
return Math.Sqrt(dX * dX + dY * dY);
}
static void Main(string[] args)
{
double n;
double c = 0.0;
double x = 0.0, y = 0.0;
double result;
string input;
Console.WriteLine("Quick, pick an integer");
input = Console.ReadLine();
n = double.Parse(input);
Random rand = new Random();
for (int i = 1; i <= n; i++)
{
x = rand.NextDouble();
y = rand.NextDouble();
if (euclideanDistance(x, y, 0, 0) <= 1)
c++;
result = 4.0 * (c / i);
Console.WriteLine("Result: " + result);
}
Console.ReadKey();
}
}
}
It coverages very slowly, I get 3.14152314152314 after 1M iterations.
I have been trying to learn more about lambda expressions lately, and thought of a interesting exercise...
is there a way to simplify a c++ integration function like this:
// Integral Function
double integrate(double a, double b, double (*f)(double))
{
double sum = 0.0;
// Evaluate integral{a,b} f(x) dx
for(int n = 0 ; n <= 100; ++n)
{
double x = a + n*(b-a)/100.0;
sum += (*f)(x) * (b-a)/101.0;
}
return sum;
}
by using c# and lambda expressions?
What about this:
public double Integrate(double a,double b, Func<double, double> f)
{
double sum = 0.0;
for (int n = 0; n <= 100; ++n)
{
double x = a + n * (b - a) / 100.0;
sum += f(x) * (b - a) / 101.0;
}
return sum;
}
Test:
Func<double, double> fun = x => Math.Pow(x,2);
double result = Integrate(0, 10, fun);
Lambda Powa! Not sure whether this is right (No C# programmer! Just liking its lambda stuff)
(a, b, c) => {
double sum = 0.0;
Func<double, double> dox = (x) => a + x*(b-a)/100.0;
// Evaluate integral{a,b} f(x) dx
for(int n = 0 ; n <= 100; ++n)
sum += c(dox(n)) * (b-a)/101.0;
return sum;
}
Ok, so i think while the code is C++, why not keep it C++ and get lambda in? Here it is how it looks for c++0x, being hopefully released as a Standard very soon :
static double Integrate(double a, double b, function<double(double)> f)
{
double sum = 0.0;
// Evaluate integral{a,b} f(x) dx
for(int n = 0; n < 100; ++n) {
double x = a + n * (b - a) / 100.0;
sum += f(x) * (b - a) / 101.0;
}
return sum;
}
int main() {
Integrate(0, 1, [](double a) { return a * a; });
}
The real power comes, as stated, when calling it. For example, in C#
static double Integrate(double a, double b, Func<double, double> func)
{
double sum = 0.0;
// Evaluate integral{a,b} f(x) dx
for(int n = 0 ; n <= 100; ++n)
{
double x = a + n*(b-a)/100.0;
sum += func(x) * (b - a) / 101.0;
}
return sum;
}
Then:
double value = Integrate(1,2,x=>x*x); // yields 2.335
// expect C+(x^3)/3, i.e. 8/3-1/3=7/3=2.33...