我目前正在通过在 Scala 中编写尾递归来计算两个自然数的二项式系数。但是我的代码在除数方面有问题,整数除以 k 就像我所做的那样,因为这会给你一个非零余数,从而引入舍入错误。那么有人可以帮我解决这个问题吗?
def binom(n: Int, k: Int): Int = {
require(0 <= k && k <= n)
def binomtail(n: Int, k: Int, ac: Int): Int = {
if (n == k || k == 0) ac
else binomtail(n - 1, k - 1, (n*ac)/k)
}
binomtail(n,k,1)
}
Run Code Online (Sandbox Code Playgroud) 我正在将以下 python 计算的结果与 Mathematica 进行比较:https://www.wolframalpha.com/input ?i=sum+%28500+choose+r+%29%28-1%29%5Er+%2F%28r%21 %29+%2C+r%3D0+至+500
import numpy as np
from decimal import *
import scipy.special
from scipy.special import factorial
getcontext().prec = 30
i = 500
sum(np.array([scipy.special.comb(Decimal(i), (r), exact=True)*pow(-1, r)/Decimal(factorial(r, exact=False)) for r in range(i+1)]))
Run Code Online (Sandbox Code Playgroud)
尽管我通过模块在 python 代码中设置了任意精度,但这两个计算都给出了几乎相同的值,i = 400但之后未能收敛decimal。用 Mathematica 计算似乎是正确的。我想知道,对于更大的数据,我们怎样才能在 python 中得到与 Mathematica 相同的结果呢i?
python precision wolfram-mathematica numpy binomial-coefficients
有a/b mod m = (a mod m)/(b mod m)吗?
我试图为非常大的数字找到nCr mod m.如果a/b mod m = (a mod m)/(b mod m)那时认为我会解决我的问题.
这是项目欧拉.我正在使用使用阶乘的nCr公式.
二项式是:(x-3)(x5)
import math
print " This program will find the binomials of an equation."
a = int(raw_input('Enter the first coefficient'))
b = int(raw_input('Enter the second coefficient'))
c = int(raw_input('Enter the third term'))
firstbinomial=str(int((((b*-1)+math.sqrt((b**2)-(4*a*c)))/(2*a))*-1))
secondbinomial=str(int((((b*-1)-math.sqrt((b**2)-(4*a*c)))/(2*a))*-1))
print"The binomials are: (x"+firstbinomial+")(x"+secondbinomial")"
Run Code Online (Sandbox Code Playgroud)
import math
print " This program will find the binomials of an equation."
a = int(raw_input('Enter the first coefficient'))
b = int(raw_input('Enter the second coefficient'))
c = int(raw_input('Enter the third term'))
firstbinomial=str(int((((b*-1)+math.sqrt((b**2)-(4*a*c)))/(2*a))*-1))
if firstbinomial<=0:
sign=""
else:
sign="+"
secondbinomial=str(int((((b*-1)-math.sqrt((b**2)-(4*a*c)))/(2*a))*-1)) …Run Code Online (Sandbox Code Playgroud) 我知道如何计算choose(5,2)的二项式系数,但现在我想知道是否有一个函数可以在python或R编程语言中计算choose(5,2.1)?
初学者在这里试图了解bug的来源.
我已经写了这个递归函数来找到两个数字之间的二项式系数,这在概念上显然是正确的.然而,对于这两个数字,n = 4和k = 2,我应该得到6,而我实际得到16.任何想法为什么会发生这种情况?
#include<stdio.h>
int binomial(int n, int k)
{
if ((k = 0) || (k == n))
return 1;
if (k>n)
return 0;
return binomial(n - 1, k - 1) + binomial(n - 1, k);
}
int main()
{
int a, b, res;
a = 4;
b = 2;
res = binomial(a, b);
printf("The result is %d", res);
return 0;
}
Run Code Online (Sandbox Code Playgroud) 这是我的代码:
#include <iostream>
using namespace std;
int main()
{
int n,k,i,x;
cout << "Enter a row number for Pascal's Triangle: ";
cin >> n;
for(i=0;i<=n;i++)
{
x=1;
for(k=0;k<=i;k++)
{
cout << x << '\t';
x = x * (i - k) / (k + 1);
}
cout << endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如何更改它以便它只显示第n行而不是整个三角形?TIA.