How Can I Write this Formula in C#? (What is wrong with The way I code ?)
Hope your ok
I'll be happy if you help me out with this problem ... Thnx
I wrote this Code for the Formula : "http://up.upinja.com/zvhev.png"
Console.WriteLine("Enter two Numbers to start the Equation (X=Number , N=Power)" + "");
int X = int.Parse(Console.ReadLine());
int N = int.Parse(Console.ReadLine());
double sum = 0;
double up = 1;
int down = 1;
double sentence;
for (int i = 1; i < N; i++)
{
up = Math.Pow(X, N);
down = N * i;
sentence = up / down;
sum += sentence;
}
Console.WriteLine("The Sum is : " + sum);
I want that math Formula to be done in C# way....
my Code is running but wrong answer I get ...
Could you plz help me to fix it ?
c# math formula
add a comment |
Hope your ok
I'll be happy if you help me out with this problem ... Thnx
I wrote this Code for the Formula : "http://up.upinja.com/zvhev.png"
Console.WriteLine("Enter two Numbers to start the Equation (X=Number , N=Power)" + "");
int X = int.Parse(Console.ReadLine());
int N = int.Parse(Console.ReadLine());
double sum = 0;
double up = 1;
int down = 1;
double sentence;
for (int i = 1; i < N; i++)
{
up = Math.Pow(X, N);
down = N * i;
sentence = up / down;
sum += sentence;
}
Console.WriteLine("The Sum is : " + sum);
I want that math Formula to be done in C# way....
my Code is running but wrong answer I get ...
Could you plz help me to fix it ?
c# math formula
Please provide sample input, current output and expected output
– Camilo Terevinto
Nov 22 at 23:53
Yourdownis wrong. For example4!should be4*3*2*1and not4*i
– DavidG
Nov 22 at 23:57
Yourdowncalculation looks to be incorrect. The formula you link indicates it should bei!in each loop. Instead you're doingN * i. Also your loop should befor (int i = 1; i <= N; i++) {...}
– lumberjack4
Nov 22 at 23:58
In the first place, you get the wrong result, because your denominator (variabledown) is wrong. According to the image, the denominator is supposed to equal the factorial of the counter, i.e. in mathematical terms down = i!. (Beware: The exclamation mark is not the correct C# operator). As a quick solution you can insert a nested loop that iterates over j from 1 to i and multiplies all the j's. However, I do not recommend to do it, because the overall formula does not seem to be numerical stable. Even after you have fixed the obvious errors in your formula, the results might surprise you.
– user2690527
Nov 23 at 0:18
up = Math.Pow(X, i); down = down * i;... andi <= Nbut it will work only for small N (<13)... changingdowntodoublewould help a liitle bit but still ...
– Selvin
Nov 23 at 0:20
add a comment |
Hope your ok
I'll be happy if you help me out with this problem ... Thnx
I wrote this Code for the Formula : "http://up.upinja.com/zvhev.png"
Console.WriteLine("Enter two Numbers to start the Equation (X=Number , N=Power)" + "");
int X = int.Parse(Console.ReadLine());
int N = int.Parse(Console.ReadLine());
double sum = 0;
double up = 1;
int down = 1;
double sentence;
for (int i = 1; i < N; i++)
{
up = Math.Pow(X, N);
down = N * i;
sentence = up / down;
sum += sentence;
}
Console.WriteLine("The Sum is : " + sum);
I want that math Formula to be done in C# way....
my Code is running but wrong answer I get ...
Could you plz help me to fix it ?
c# math formula
Hope your ok
I'll be happy if you help me out with this problem ... Thnx
I wrote this Code for the Formula : "http://up.upinja.com/zvhev.png"
Console.WriteLine("Enter two Numbers to start the Equation (X=Number , N=Power)" + "");
int X = int.Parse(Console.ReadLine());
int N = int.Parse(Console.ReadLine());
double sum = 0;
double up = 1;
int down = 1;
double sentence;
for (int i = 1; i < N; i++)
{
up = Math.Pow(X, N);
down = N * i;
sentence = up / down;
sum += sentence;
}
Console.WriteLine("The Sum is : " + sum);
I want that math Formula to be done in C# way....
my Code is running but wrong answer I get ...
Could you plz help me to fix it ?
c# math formula
c# math formula
asked Nov 22 at 23:52
MeTe12
1
1
Please provide sample input, current output and expected output
– Camilo Terevinto
Nov 22 at 23:53
Yourdownis wrong. For example4!should be4*3*2*1and not4*i
– DavidG
Nov 22 at 23:57
Yourdowncalculation looks to be incorrect. The formula you link indicates it should bei!in each loop. Instead you're doingN * i. Also your loop should befor (int i = 1; i <= N; i++) {...}
– lumberjack4
Nov 22 at 23:58
In the first place, you get the wrong result, because your denominator (variabledown) is wrong. According to the image, the denominator is supposed to equal the factorial of the counter, i.e. in mathematical terms down = i!. (Beware: The exclamation mark is not the correct C# operator). As a quick solution you can insert a nested loop that iterates over j from 1 to i and multiplies all the j's. However, I do not recommend to do it, because the overall formula does not seem to be numerical stable. Even after you have fixed the obvious errors in your formula, the results might surprise you.
– user2690527
Nov 23 at 0:18
up = Math.Pow(X, i); down = down * i;... andi <= Nbut it will work only for small N (<13)... changingdowntodoublewould help a liitle bit but still ...
– Selvin
Nov 23 at 0:20
add a comment |
Please provide sample input, current output and expected output
– Camilo Terevinto
Nov 22 at 23:53
Yourdownis wrong. For example4!should be4*3*2*1and not4*i
– DavidG
Nov 22 at 23:57
Yourdowncalculation looks to be incorrect. The formula you link indicates it should bei!in each loop. Instead you're doingN * i. Also your loop should befor (int i = 1; i <= N; i++) {...}
– lumberjack4
Nov 22 at 23:58
In the first place, you get the wrong result, because your denominator (variabledown) is wrong. According to the image, the denominator is supposed to equal the factorial of the counter, i.e. in mathematical terms down = i!. (Beware: The exclamation mark is not the correct C# operator). As a quick solution you can insert a nested loop that iterates over j from 1 to i and multiplies all the j's. However, I do not recommend to do it, because the overall formula does not seem to be numerical stable. Even after you have fixed the obvious errors in your formula, the results might surprise you.
– user2690527
Nov 23 at 0:18
up = Math.Pow(X, i); down = down * i;... andi <= Nbut it will work only for small N (<13)... changingdowntodoublewould help a liitle bit but still ...
– Selvin
Nov 23 at 0:20
Please provide sample input, current output and expected output
– Camilo Terevinto
Nov 22 at 23:53
Please provide sample input, current output and expected output
– Camilo Terevinto
Nov 22 at 23:53
Your
down is wrong. For example 4! should be 4*3*2*1 and not 4*i– DavidG
Nov 22 at 23:57
Your
down is wrong. For example 4! should be 4*3*2*1 and not 4*i– DavidG
Nov 22 at 23:57
Your
down calculation looks to be incorrect. The formula you link indicates it should be i! in each loop. Instead you're doing N * i. Also your loop should be for (int i = 1; i <= N; i++) {...}– lumberjack4
Nov 22 at 23:58
Your
down calculation looks to be incorrect. The formula you link indicates it should be i! in each loop. Instead you're doing N * i. Also your loop should be for (int i = 1; i <= N; i++) {...}– lumberjack4
Nov 22 at 23:58
In the first place, you get the wrong result, because your denominator (variable
down) is wrong. According to the image, the denominator is supposed to equal the factorial of the counter, i.e. in mathematical terms down = i!. (Beware: The exclamation mark is not the correct C# operator). As a quick solution you can insert a nested loop that iterates over j from 1 to i and multiplies all the j's. However, I do not recommend to do it, because the overall formula does not seem to be numerical stable. Even after you have fixed the obvious errors in your formula, the results might surprise you.– user2690527
Nov 23 at 0:18
In the first place, you get the wrong result, because your denominator (variable
down) is wrong. According to the image, the denominator is supposed to equal the factorial of the counter, i.e. in mathematical terms down = i!. (Beware: The exclamation mark is not the correct C# operator). As a quick solution you can insert a nested loop that iterates over j from 1 to i and multiplies all the j's. However, I do not recommend to do it, because the overall formula does not seem to be numerical stable. Even after you have fixed the obvious errors in your formula, the results might surprise you.– user2690527
Nov 23 at 0:18
up = Math.Pow(X, i); down = down * i; ... and i <= N but it will work only for small N (<13)... changing down to double would help a liitle bit but still ...– Selvin
Nov 23 at 0:20
up = Math.Pow(X, i); down = down * i; ... and i <= N but it will work only for small N (<13)... changing down to double would help a liitle bit but still ...– Selvin
Nov 23 at 0:20
add a comment |
4 Answers
4
active
oldest
votes
n! represents Factorial. Please refer Factorial to read about Factorial.
A sample factorial function in C# is as follows:
long Factorial(long value)
{
if (value == 0)
return 1;
return value * Factorial(value - 1);
}
Also, following line needs correction.
up = Math.Pow(X, N);
The exponent part needs to increase according to your formula. It needs to be
up = Math.Pow(X, i);
your function is not working ... Factorial(13) returns 1 932 053 504 which is wrong
– Selvin
Nov 23 at 0:09
Ooops, thanks for pointing for Selvin. 'int' was the culprint, i have corrected the code
– Anu Viswan
Nov 23 at 0:14
now it's wrong for 21
– Selvin
Nov 23 at 0:14
@Selvin I think we can forgive that though...
– DavidG
Nov 23 at 0:18
My apologies @selvin. Limitations of the data type is obvious in the code. But crux of idea was to highlight key areas where to look at, as there was problem in the way formula was interpreted, especially exponents and factorials.
– Anu Viswan
Nov 23 at 0:21
add a comment |
Use this:
Console.WriteLine("Enter two Numbers to start the Equation (X=Number , N=Power)" + "");
int X = int.Parse(Console.ReadLine());
int N = int.Parse(Console.ReadLine());
double sum = 0;
double up = 1;
int down = 1;
double sentence;
for (int i = 1; i <= N; i++)
//Change < to <=
{
up = Math.Pow(X, i);
//This is a for loop i created to get the factorial of any number, sometimes creating your own functions may be worth it
for (int a = N, a > 0, a--)
{
//Function of this Loop : multiply the value of the denominator by its value - 1 to get the factorial of the number
down *= a;
}
sentence = up / down;
sum += sentence;
}
Console.WriteLine("The Sum is : " + sum);
Code dumps without explanation are not useful here. And what do you think this answer gives that the existing ones doesn't?
– DavidG
Nov 23 at 0:27
what do you mean "code dumps"
– preciousbetine
Nov 23 at 0:28
1
A code dump is literally that, a dump of code. In this case it means that you should explain what the code is doing, that's what makes a good answer.
– DavidG
Nov 23 at 0:31
Did you not see the comments i added in the code
– preciousbetine
Nov 23 at 0:34
add a comment |
You can actually simplify this quite a bit. But first, what's wrong with your existing code is that you're not computing i! correctly. The sequence you're actually computing right now is:
X^N / N + X^N / (2 * N) + X^N / (3 * N) + ... + X^N / ((N - 1) * N)
A few things:
- The loop has an off-by-one issue
- The numerator is raised to the wrong power
- The denominator of these needs to be i!
Factorials are defined through a simple recurrence relation:
i! = i * (i - 1)! and 0! = 1
Or, in other words, the product of the first i consecutive natural numbers. So one way to correct this is by creating a method called Factorial:
static long Factorial(int i)
{
long product = 1;
while (i > 0) {
product *= i;
--i;
}
return product;
}
Then you can fix your loop this way:
for (int i = 1; i < N; i++)
{
sum += Math.Pow(X, i) / Factorial(i);
}
However, we're redoing a lot of work every iteration of the loop that we don't need to do. This is where the simplification comes in. The general formula for the i'th term is this:
C[i] = X^i / i!
But we can also write this in terms of the term that came before it:
C[i] = C[i-1] * X / i
So we can rewrite the loop like this:
double lastTerm = 1;
for (int i = 1; i <= N; ++i)
{
// Cast to double here or, probably better, make X a double in the first place.
lastTerm *= (double) X / i;
sum += lastTerm;
}
This has several advantages:
- It'll generally be faster since we're doing less work each iteration (
Math.Powcomputes arbitrary powers, so it's a bit slower than just multiplying). - It'll be less prone to numerical issues. Factorials get really big really fast. In fact, 21! is already too big to store in a
longso if yourNis bigger than that, everything will break.
1
i<=NandXshould be double because of implication of int/int
– Selvin
Nov 23 at 0:32
@Selvin Good eye.
– Kyle
Nov 23 at 1:10
and for large N it's juste^X-1
– Selvin
Nov 23 at 1:11
Also correct, but I figured the point of the exercise was as part of a demonstration of that fact by being able to compute the partial sums, so I didn't mention it.
– Kyle
Nov 23 at 1:13
add a comment |
Something wrong in pow, shoud incremental value
up = Math.Pow(X, i);
1
Note that you're getting downvotes because your answer is simply wrong.
– DavidG
Nov 23 at 0:02
1
You can't just fix one tiny part and expect that to be enough. Answers need to be complete.
– DavidG
Nov 23 at 0:13
1
Answers need to be complete or they are not useful. What you have said is correct, but you could have written that as a comment as it doesn't answer the question being asked. I'm not trying to be mean here, but I've been around long enough to know what makes a good answer...
– DavidG
Nov 23 at 0:24
1
OK, I've tried to help you but you're not listening. Now you have 3 people all agreeing that this is a bad answer. As for the question you link, look how much detail is in those answers?
– DavidG
Nov 23 at 0:34
1
Oh the irony, comparing any of the answers in those question with what you have provided as "answer" here. It boggles my mind. Any of those answers provide orders of magniture more information, knowledge and context with regard to "their" question than the two-liner here does for the question at hand. Yet here we are, pretending those other answers are in some shape or form similar to this one here.
– elgonzo
Nov 23 at 0:37
|
show 3 more comments
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53439199%2fhow-can-i-write-this-formula-in-c-what-is-wrong-with-the-way-i-code%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
4 Answers
4
active
oldest
votes
4 Answers
4
active
oldest
votes
active
oldest
votes
active
oldest
votes
n! represents Factorial. Please refer Factorial to read about Factorial.
A sample factorial function in C# is as follows:
long Factorial(long value)
{
if (value == 0)
return 1;
return value * Factorial(value - 1);
}
Also, following line needs correction.
up = Math.Pow(X, N);
The exponent part needs to increase according to your formula. It needs to be
up = Math.Pow(X, i);
your function is not working ... Factorial(13) returns 1 932 053 504 which is wrong
– Selvin
Nov 23 at 0:09
Ooops, thanks for pointing for Selvin. 'int' was the culprint, i have corrected the code
– Anu Viswan
Nov 23 at 0:14
now it's wrong for 21
– Selvin
Nov 23 at 0:14
@Selvin I think we can forgive that though...
– DavidG
Nov 23 at 0:18
My apologies @selvin. Limitations of the data type is obvious in the code. But crux of idea was to highlight key areas where to look at, as there was problem in the way formula was interpreted, especially exponents and factorials.
– Anu Viswan
Nov 23 at 0:21
add a comment |
n! represents Factorial. Please refer Factorial to read about Factorial.
A sample factorial function in C# is as follows:
long Factorial(long value)
{
if (value == 0)
return 1;
return value * Factorial(value - 1);
}
Also, following line needs correction.
up = Math.Pow(X, N);
The exponent part needs to increase according to your formula. It needs to be
up = Math.Pow(X, i);
your function is not working ... Factorial(13) returns 1 932 053 504 which is wrong
– Selvin
Nov 23 at 0:09
Ooops, thanks for pointing for Selvin. 'int' was the culprint, i have corrected the code
– Anu Viswan
Nov 23 at 0:14
now it's wrong for 21
– Selvin
Nov 23 at 0:14
@Selvin I think we can forgive that though...
– DavidG
Nov 23 at 0:18
My apologies @selvin. Limitations of the data type is obvious in the code. But crux of idea was to highlight key areas where to look at, as there was problem in the way formula was interpreted, especially exponents and factorials.
– Anu Viswan
Nov 23 at 0:21
add a comment |
n! represents Factorial. Please refer Factorial to read about Factorial.
A sample factorial function in C# is as follows:
long Factorial(long value)
{
if (value == 0)
return 1;
return value * Factorial(value - 1);
}
Also, following line needs correction.
up = Math.Pow(X, N);
The exponent part needs to increase according to your formula. It needs to be
up = Math.Pow(X, i);
n! represents Factorial. Please refer Factorial to read about Factorial.
A sample factorial function in C# is as follows:
long Factorial(long value)
{
if (value == 0)
return 1;
return value * Factorial(value - 1);
}
Also, following line needs correction.
up = Math.Pow(X, N);
The exponent part needs to increase according to your formula. It needs to be
up = Math.Pow(X, i);
edited Nov 23 at 0:15
answered Nov 22 at 23:59
Anu Viswan
1,6161518
1,6161518
your function is not working ... Factorial(13) returns 1 932 053 504 which is wrong
– Selvin
Nov 23 at 0:09
Ooops, thanks for pointing for Selvin. 'int' was the culprint, i have corrected the code
– Anu Viswan
Nov 23 at 0:14
now it's wrong for 21
– Selvin
Nov 23 at 0:14
@Selvin I think we can forgive that though...
– DavidG
Nov 23 at 0:18
My apologies @selvin. Limitations of the data type is obvious in the code. But crux of idea was to highlight key areas where to look at, as there was problem in the way formula was interpreted, especially exponents and factorials.
– Anu Viswan
Nov 23 at 0:21
add a comment |
your function is not working ... Factorial(13) returns 1 932 053 504 which is wrong
– Selvin
Nov 23 at 0:09
Ooops, thanks for pointing for Selvin. 'int' was the culprint, i have corrected the code
– Anu Viswan
Nov 23 at 0:14
now it's wrong for 21
– Selvin
Nov 23 at 0:14
@Selvin I think we can forgive that though...
– DavidG
Nov 23 at 0:18
My apologies @selvin. Limitations of the data type is obvious in the code. But crux of idea was to highlight key areas where to look at, as there was problem in the way formula was interpreted, especially exponents and factorials.
– Anu Viswan
Nov 23 at 0:21
your function is not working ... Factorial(13) returns 1 932 053 504 which is wrong
– Selvin
Nov 23 at 0:09
your function is not working ... Factorial(13) returns 1 932 053 504 which is wrong
– Selvin
Nov 23 at 0:09
Ooops, thanks for pointing for Selvin. 'int' was the culprint, i have corrected the code
– Anu Viswan
Nov 23 at 0:14
Ooops, thanks for pointing for Selvin. 'int' was the culprint, i have corrected the code
– Anu Viswan
Nov 23 at 0:14
now it's wrong for 21
– Selvin
Nov 23 at 0:14
now it's wrong for 21
– Selvin
Nov 23 at 0:14
@Selvin I think we can forgive that though...
– DavidG
Nov 23 at 0:18
@Selvin I think we can forgive that though...
– DavidG
Nov 23 at 0:18
My apologies @selvin. Limitations of the data type is obvious in the code. But crux of idea was to highlight key areas where to look at, as there was problem in the way formula was interpreted, especially exponents and factorials.
– Anu Viswan
Nov 23 at 0:21
My apologies @selvin. Limitations of the data type is obvious in the code. But crux of idea was to highlight key areas where to look at, as there was problem in the way formula was interpreted, especially exponents and factorials.
– Anu Viswan
Nov 23 at 0:21
add a comment |
Use this:
Console.WriteLine("Enter two Numbers to start the Equation (X=Number , N=Power)" + "");
int X = int.Parse(Console.ReadLine());
int N = int.Parse(Console.ReadLine());
double sum = 0;
double up = 1;
int down = 1;
double sentence;
for (int i = 1; i <= N; i++)
//Change < to <=
{
up = Math.Pow(X, i);
//This is a for loop i created to get the factorial of any number, sometimes creating your own functions may be worth it
for (int a = N, a > 0, a--)
{
//Function of this Loop : multiply the value of the denominator by its value - 1 to get the factorial of the number
down *= a;
}
sentence = up / down;
sum += sentence;
}
Console.WriteLine("The Sum is : " + sum);
Code dumps without explanation are not useful here. And what do you think this answer gives that the existing ones doesn't?
– DavidG
Nov 23 at 0:27
what do you mean "code dumps"
– preciousbetine
Nov 23 at 0:28
1
A code dump is literally that, a dump of code. In this case it means that you should explain what the code is doing, that's what makes a good answer.
– DavidG
Nov 23 at 0:31
Did you not see the comments i added in the code
– preciousbetine
Nov 23 at 0:34
add a comment |
Use this:
Console.WriteLine("Enter two Numbers to start the Equation (X=Number , N=Power)" + "");
int X = int.Parse(Console.ReadLine());
int N = int.Parse(Console.ReadLine());
double sum = 0;
double up = 1;
int down = 1;
double sentence;
for (int i = 1; i <= N; i++)
//Change < to <=
{
up = Math.Pow(X, i);
//This is a for loop i created to get the factorial of any number, sometimes creating your own functions may be worth it
for (int a = N, a > 0, a--)
{
//Function of this Loop : multiply the value of the denominator by its value - 1 to get the factorial of the number
down *= a;
}
sentence = up / down;
sum += sentence;
}
Console.WriteLine("The Sum is : " + sum);
Code dumps without explanation are not useful here. And what do you think this answer gives that the existing ones doesn't?
– DavidG
Nov 23 at 0:27
what do you mean "code dumps"
– preciousbetine
Nov 23 at 0:28
1
A code dump is literally that, a dump of code. In this case it means that you should explain what the code is doing, that's what makes a good answer.
– DavidG
Nov 23 at 0:31
Did you not see the comments i added in the code
– preciousbetine
Nov 23 at 0:34
add a comment |
Use this:
Console.WriteLine("Enter two Numbers to start the Equation (X=Number , N=Power)" + "");
int X = int.Parse(Console.ReadLine());
int N = int.Parse(Console.ReadLine());
double sum = 0;
double up = 1;
int down = 1;
double sentence;
for (int i = 1; i <= N; i++)
//Change < to <=
{
up = Math.Pow(X, i);
//This is a for loop i created to get the factorial of any number, sometimes creating your own functions may be worth it
for (int a = N, a > 0, a--)
{
//Function of this Loop : multiply the value of the denominator by its value - 1 to get the factorial of the number
down *= a;
}
sentence = up / down;
sum += sentence;
}
Console.WriteLine("The Sum is : " + sum);
Use this:
Console.WriteLine("Enter two Numbers to start the Equation (X=Number , N=Power)" + "");
int X = int.Parse(Console.ReadLine());
int N = int.Parse(Console.ReadLine());
double sum = 0;
double up = 1;
int down = 1;
double sentence;
for (int i = 1; i <= N; i++)
//Change < to <=
{
up = Math.Pow(X, i);
//This is a for loop i created to get the factorial of any number, sometimes creating your own functions may be worth it
for (int a = N, a > 0, a--)
{
//Function of this Loop : multiply the value of the denominator by its value - 1 to get the factorial of the number
down *= a;
}
sentence = up / down;
sum += sentence;
}
Console.WriteLine("The Sum is : " + sum);
edited Nov 23 at 0:28
answered Nov 23 at 0:27
preciousbetine
590113
590113
Code dumps without explanation are not useful here. And what do you think this answer gives that the existing ones doesn't?
– DavidG
Nov 23 at 0:27
what do you mean "code dumps"
– preciousbetine
Nov 23 at 0:28
1
A code dump is literally that, a dump of code. In this case it means that you should explain what the code is doing, that's what makes a good answer.
– DavidG
Nov 23 at 0:31
Did you not see the comments i added in the code
– preciousbetine
Nov 23 at 0:34
add a comment |
Code dumps without explanation are not useful here. And what do you think this answer gives that the existing ones doesn't?
– DavidG
Nov 23 at 0:27
what do you mean "code dumps"
– preciousbetine
Nov 23 at 0:28
1
A code dump is literally that, a dump of code. In this case it means that you should explain what the code is doing, that's what makes a good answer.
– DavidG
Nov 23 at 0:31
Did you not see the comments i added in the code
– preciousbetine
Nov 23 at 0:34
Code dumps without explanation are not useful here. And what do you think this answer gives that the existing ones doesn't?
– DavidG
Nov 23 at 0:27
Code dumps without explanation are not useful here. And what do you think this answer gives that the existing ones doesn't?
– DavidG
Nov 23 at 0:27
what do you mean "code dumps"
– preciousbetine
Nov 23 at 0:28
what do you mean "code dumps"
– preciousbetine
Nov 23 at 0:28
1
1
A code dump is literally that, a dump of code. In this case it means that you should explain what the code is doing, that's what makes a good answer.
– DavidG
Nov 23 at 0:31
A code dump is literally that, a dump of code. In this case it means that you should explain what the code is doing, that's what makes a good answer.
– DavidG
Nov 23 at 0:31
Did you not see the comments i added in the code
– preciousbetine
Nov 23 at 0:34
Did you not see the comments i added in the code
– preciousbetine
Nov 23 at 0:34
add a comment |
You can actually simplify this quite a bit. But first, what's wrong with your existing code is that you're not computing i! correctly. The sequence you're actually computing right now is:
X^N / N + X^N / (2 * N) + X^N / (3 * N) + ... + X^N / ((N - 1) * N)
A few things:
- The loop has an off-by-one issue
- The numerator is raised to the wrong power
- The denominator of these needs to be i!
Factorials are defined through a simple recurrence relation:
i! = i * (i - 1)! and 0! = 1
Or, in other words, the product of the first i consecutive natural numbers. So one way to correct this is by creating a method called Factorial:
static long Factorial(int i)
{
long product = 1;
while (i > 0) {
product *= i;
--i;
}
return product;
}
Then you can fix your loop this way:
for (int i = 1; i < N; i++)
{
sum += Math.Pow(X, i) / Factorial(i);
}
However, we're redoing a lot of work every iteration of the loop that we don't need to do. This is where the simplification comes in. The general formula for the i'th term is this:
C[i] = X^i / i!
But we can also write this in terms of the term that came before it:
C[i] = C[i-1] * X / i
So we can rewrite the loop like this:
double lastTerm = 1;
for (int i = 1; i <= N; ++i)
{
// Cast to double here or, probably better, make X a double in the first place.
lastTerm *= (double) X / i;
sum += lastTerm;
}
This has several advantages:
- It'll generally be faster since we're doing less work each iteration (
Math.Powcomputes arbitrary powers, so it's a bit slower than just multiplying). - It'll be less prone to numerical issues. Factorials get really big really fast. In fact, 21! is already too big to store in a
longso if yourNis bigger than that, everything will break.
1
i<=NandXshould be double because of implication of int/int
– Selvin
Nov 23 at 0:32
@Selvin Good eye.
– Kyle
Nov 23 at 1:10
and for large N it's juste^X-1
– Selvin
Nov 23 at 1:11
Also correct, but I figured the point of the exercise was as part of a demonstration of that fact by being able to compute the partial sums, so I didn't mention it.
– Kyle
Nov 23 at 1:13
add a comment |
You can actually simplify this quite a bit. But first, what's wrong with your existing code is that you're not computing i! correctly. The sequence you're actually computing right now is:
X^N / N + X^N / (2 * N) + X^N / (3 * N) + ... + X^N / ((N - 1) * N)
A few things:
- The loop has an off-by-one issue
- The numerator is raised to the wrong power
- The denominator of these needs to be i!
Factorials are defined through a simple recurrence relation:
i! = i * (i - 1)! and 0! = 1
Or, in other words, the product of the first i consecutive natural numbers. So one way to correct this is by creating a method called Factorial:
static long Factorial(int i)
{
long product = 1;
while (i > 0) {
product *= i;
--i;
}
return product;
}
Then you can fix your loop this way:
for (int i = 1; i < N; i++)
{
sum += Math.Pow(X, i) / Factorial(i);
}
However, we're redoing a lot of work every iteration of the loop that we don't need to do. This is where the simplification comes in. The general formula for the i'th term is this:
C[i] = X^i / i!
But we can also write this in terms of the term that came before it:
C[i] = C[i-1] * X / i
So we can rewrite the loop like this:
double lastTerm = 1;
for (int i = 1; i <= N; ++i)
{
// Cast to double here or, probably better, make X a double in the first place.
lastTerm *= (double) X / i;
sum += lastTerm;
}
This has several advantages:
- It'll generally be faster since we're doing less work each iteration (
Math.Powcomputes arbitrary powers, so it's a bit slower than just multiplying). - It'll be less prone to numerical issues. Factorials get really big really fast. In fact, 21! is already too big to store in a
longso if yourNis bigger than that, everything will break.
1
i<=NandXshould be double because of implication of int/int
– Selvin
Nov 23 at 0:32
@Selvin Good eye.
– Kyle
Nov 23 at 1:10
and for large N it's juste^X-1
– Selvin
Nov 23 at 1:11
Also correct, but I figured the point of the exercise was as part of a demonstration of that fact by being able to compute the partial sums, so I didn't mention it.
– Kyle
Nov 23 at 1:13
add a comment |
You can actually simplify this quite a bit. But first, what's wrong with your existing code is that you're not computing i! correctly. The sequence you're actually computing right now is:
X^N / N + X^N / (2 * N) + X^N / (3 * N) + ... + X^N / ((N - 1) * N)
A few things:
- The loop has an off-by-one issue
- The numerator is raised to the wrong power
- The denominator of these needs to be i!
Factorials are defined through a simple recurrence relation:
i! = i * (i - 1)! and 0! = 1
Or, in other words, the product of the first i consecutive natural numbers. So one way to correct this is by creating a method called Factorial:
static long Factorial(int i)
{
long product = 1;
while (i > 0) {
product *= i;
--i;
}
return product;
}
Then you can fix your loop this way:
for (int i = 1; i < N; i++)
{
sum += Math.Pow(X, i) / Factorial(i);
}
However, we're redoing a lot of work every iteration of the loop that we don't need to do. This is where the simplification comes in. The general formula for the i'th term is this:
C[i] = X^i / i!
But we can also write this in terms of the term that came before it:
C[i] = C[i-1] * X / i
So we can rewrite the loop like this:
double lastTerm = 1;
for (int i = 1; i <= N; ++i)
{
// Cast to double here or, probably better, make X a double in the first place.
lastTerm *= (double) X / i;
sum += lastTerm;
}
This has several advantages:
- It'll generally be faster since we're doing less work each iteration (
Math.Powcomputes arbitrary powers, so it's a bit slower than just multiplying). - It'll be less prone to numerical issues. Factorials get really big really fast. In fact, 21! is already too big to store in a
longso if yourNis bigger than that, everything will break.
You can actually simplify this quite a bit. But first, what's wrong with your existing code is that you're not computing i! correctly. The sequence you're actually computing right now is:
X^N / N + X^N / (2 * N) + X^N / (3 * N) + ... + X^N / ((N - 1) * N)
A few things:
- The loop has an off-by-one issue
- The numerator is raised to the wrong power
- The denominator of these needs to be i!
Factorials are defined through a simple recurrence relation:
i! = i * (i - 1)! and 0! = 1
Or, in other words, the product of the first i consecutive natural numbers. So one way to correct this is by creating a method called Factorial:
static long Factorial(int i)
{
long product = 1;
while (i > 0) {
product *= i;
--i;
}
return product;
}
Then you can fix your loop this way:
for (int i = 1; i < N; i++)
{
sum += Math.Pow(X, i) / Factorial(i);
}
However, we're redoing a lot of work every iteration of the loop that we don't need to do. This is where the simplification comes in. The general formula for the i'th term is this:
C[i] = X^i / i!
But we can also write this in terms of the term that came before it:
C[i] = C[i-1] * X / i
So we can rewrite the loop like this:
double lastTerm = 1;
for (int i = 1; i <= N; ++i)
{
// Cast to double here or, probably better, make X a double in the first place.
lastTerm *= (double) X / i;
sum += lastTerm;
}
This has several advantages:
- It'll generally be faster since we're doing less work each iteration (
Math.Powcomputes arbitrary powers, so it's a bit slower than just multiplying). - It'll be less prone to numerical issues. Factorials get really big really fast. In fact, 21! is already too big to store in a
longso if yourNis bigger than that, everything will break.
edited Nov 23 at 1:12
answered Nov 23 at 0:28
Kyle
4,25122033
4,25122033
1
i<=NandXshould be double because of implication of int/int
– Selvin
Nov 23 at 0:32
@Selvin Good eye.
– Kyle
Nov 23 at 1:10
and for large N it's juste^X-1
– Selvin
Nov 23 at 1:11
Also correct, but I figured the point of the exercise was as part of a demonstration of that fact by being able to compute the partial sums, so I didn't mention it.
– Kyle
Nov 23 at 1:13
add a comment |
1
i<=NandXshould be double because of implication of int/int
– Selvin
Nov 23 at 0:32
@Selvin Good eye.
– Kyle
Nov 23 at 1:10
and for large N it's juste^X-1
– Selvin
Nov 23 at 1:11
Also correct, but I figured the point of the exercise was as part of a demonstration of that fact by being able to compute the partial sums, so I didn't mention it.
– Kyle
Nov 23 at 1:13
1
1
i<=N and X should be double because of implication of int/int– Selvin
Nov 23 at 0:32
i<=N and X should be double because of implication of int/int– Selvin
Nov 23 at 0:32
@Selvin Good eye.
– Kyle
Nov 23 at 1:10
@Selvin Good eye.
– Kyle
Nov 23 at 1:10
and for large N it's just
e^X-1– Selvin
Nov 23 at 1:11
and for large N it's just
e^X-1– Selvin
Nov 23 at 1:11
Also correct, but I figured the point of the exercise was as part of a demonstration of that fact by being able to compute the partial sums, so I didn't mention it.
– Kyle
Nov 23 at 1:13
Also correct, but I figured the point of the exercise was as part of a demonstration of that fact by being able to compute the partial sums, so I didn't mention it.
– Kyle
Nov 23 at 1:13
add a comment |
Something wrong in pow, shoud incremental value
up = Math.Pow(X, i);
1
Note that you're getting downvotes because your answer is simply wrong.
– DavidG
Nov 23 at 0:02
1
You can't just fix one tiny part and expect that to be enough. Answers need to be complete.
– DavidG
Nov 23 at 0:13
1
Answers need to be complete or they are not useful. What you have said is correct, but you could have written that as a comment as it doesn't answer the question being asked. I'm not trying to be mean here, but I've been around long enough to know what makes a good answer...
– DavidG
Nov 23 at 0:24
1
OK, I've tried to help you but you're not listening. Now you have 3 people all agreeing that this is a bad answer. As for the question you link, look how much detail is in those answers?
– DavidG
Nov 23 at 0:34
1
Oh the irony, comparing any of the answers in those question with what you have provided as "answer" here. It boggles my mind. Any of those answers provide orders of magniture more information, knowledge and context with regard to "their" question than the two-liner here does for the question at hand. Yet here we are, pretending those other answers are in some shape or form similar to this one here.
– elgonzo
Nov 23 at 0:37
|
show 3 more comments
Something wrong in pow, shoud incremental value
up = Math.Pow(X, i);
1
Note that you're getting downvotes because your answer is simply wrong.
– DavidG
Nov 23 at 0:02
1
You can't just fix one tiny part and expect that to be enough. Answers need to be complete.
– DavidG
Nov 23 at 0:13
1
Answers need to be complete or they are not useful. What you have said is correct, but you could have written that as a comment as it doesn't answer the question being asked. I'm not trying to be mean here, but I've been around long enough to know what makes a good answer...
– DavidG
Nov 23 at 0:24
1
OK, I've tried to help you but you're not listening. Now you have 3 people all agreeing that this is a bad answer. As for the question you link, look how much detail is in those answers?
– DavidG
Nov 23 at 0:34
1
Oh the irony, comparing any of the answers in those question with what you have provided as "answer" here. It boggles my mind. Any of those answers provide orders of magniture more information, knowledge and context with regard to "their" question than the two-liner here does for the question at hand. Yet here we are, pretending those other answers are in some shape or form similar to this one here.
– elgonzo
Nov 23 at 0:37
|
show 3 more comments
Something wrong in pow, shoud incremental value
up = Math.Pow(X, i);
Something wrong in pow, shoud incremental value
up = Math.Pow(X, i);
edited Nov 23 at 0:09
answered Nov 22 at 23:58
Lemons
49110
49110
1
Note that you're getting downvotes because your answer is simply wrong.
– DavidG
Nov 23 at 0:02
1
You can't just fix one tiny part and expect that to be enough. Answers need to be complete.
– DavidG
Nov 23 at 0:13
1
Answers need to be complete or they are not useful. What you have said is correct, but you could have written that as a comment as it doesn't answer the question being asked. I'm not trying to be mean here, but I've been around long enough to know what makes a good answer...
– DavidG
Nov 23 at 0:24
1
OK, I've tried to help you but you're not listening. Now you have 3 people all agreeing that this is a bad answer. As for the question you link, look how much detail is in those answers?
– DavidG
Nov 23 at 0:34
1
Oh the irony, comparing any of the answers in those question with what you have provided as "answer" here. It boggles my mind. Any of those answers provide orders of magniture more information, knowledge and context with regard to "their" question than the two-liner here does for the question at hand. Yet here we are, pretending those other answers are in some shape or form similar to this one here.
– elgonzo
Nov 23 at 0:37
|
show 3 more comments
1
Note that you're getting downvotes because your answer is simply wrong.
– DavidG
Nov 23 at 0:02
1
You can't just fix one tiny part and expect that to be enough. Answers need to be complete.
– DavidG
Nov 23 at 0:13
1
Answers need to be complete or they are not useful. What you have said is correct, but you could have written that as a comment as it doesn't answer the question being asked. I'm not trying to be mean here, but I've been around long enough to know what makes a good answer...
– DavidG
Nov 23 at 0:24
1
OK, I've tried to help you but you're not listening. Now you have 3 people all agreeing that this is a bad answer. As for the question you link, look how much detail is in those answers?
– DavidG
Nov 23 at 0:34
1
Oh the irony, comparing any of the answers in those question with what you have provided as "answer" here. It boggles my mind. Any of those answers provide orders of magniture more information, knowledge and context with regard to "their" question than the two-liner here does for the question at hand. Yet here we are, pretending those other answers are in some shape or form similar to this one here.
– elgonzo
Nov 23 at 0:37
1
1
Note that you're getting downvotes because your answer is simply wrong.
– DavidG
Nov 23 at 0:02
Note that you're getting downvotes because your answer is simply wrong.
– DavidG
Nov 23 at 0:02
1
1
You can't just fix one tiny part and expect that to be enough. Answers need to be complete.
– DavidG
Nov 23 at 0:13
You can't just fix one tiny part and expect that to be enough. Answers need to be complete.
– DavidG
Nov 23 at 0:13
1
1
Answers need to be complete or they are not useful. What you have said is correct, but you could have written that as a comment as it doesn't answer the question being asked. I'm not trying to be mean here, but I've been around long enough to know what makes a good answer...
– DavidG
Nov 23 at 0:24
Answers need to be complete or they are not useful. What you have said is correct, but you could have written that as a comment as it doesn't answer the question being asked. I'm not trying to be mean here, but I've been around long enough to know what makes a good answer...
– DavidG
Nov 23 at 0:24
1
1
OK, I've tried to help you but you're not listening. Now you have 3 people all agreeing that this is a bad answer. As for the question you link, look how much detail is in those answers?
– DavidG
Nov 23 at 0:34
OK, I've tried to help you but you're not listening. Now you have 3 people all agreeing that this is a bad answer. As for the question you link, look how much detail is in those answers?
– DavidG
Nov 23 at 0:34
1
1
Oh the irony, comparing any of the answers in those question with what you have provided as "answer" here. It boggles my mind. Any of those answers provide orders of magniture more information, knowledge and context with regard to "their" question than the two-liner here does for the question at hand. Yet here we are, pretending those other answers are in some shape or form similar to this one here.
– elgonzo
Nov 23 at 0:37
Oh the irony, comparing any of the answers in those question with what you have provided as "answer" here. It boggles my mind. Any of those answers provide orders of magniture more information, knowledge and context with regard to "their" question than the two-liner here does for the question at hand. Yet here we are, pretending those other answers are in some shape or form similar to this one here.
– elgonzo
Nov 23 at 0:37
|
show 3 more comments
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53439199%2fhow-can-i-write-this-formula-in-c-what-is-wrong-with-the-way-i-code%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Please provide sample input, current output and expected output
– Camilo Terevinto
Nov 22 at 23:53
Your
downis wrong. For example4!should be4*3*2*1and not4*i– DavidG
Nov 22 at 23:57
Your
downcalculation looks to be incorrect. The formula you link indicates it should bei!in each loop. Instead you're doingN * i. Also your loop should befor (int i = 1; i <= N; i++) {...}– lumberjack4
Nov 22 at 23:58
In the first place, you get the wrong result, because your denominator (variable
down) is wrong. According to the image, the denominator is supposed to equal the factorial of the counter, i.e. in mathematical terms down = i!. (Beware: The exclamation mark is not the correct C# operator). As a quick solution you can insert a nested loop that iterates over j from 1 to i and multiplies all the j's. However, I do not recommend to do it, because the overall formula does not seem to be numerical stable. Even after you have fixed the obvious errors in your formula, the results might surprise you.– user2690527
Nov 23 at 0:18
up = Math.Pow(X, i); down = down * i;... andi <= Nbut it will work only for small N (<13)... changingdowntodoublewould help a liitle bit but still ...– Selvin
Nov 23 at 0:20