📜  四次方程根的和与积之间的绝对差

📅  最后修改于: 2021-04-22 08:27:10             🧑  作者: Mango

给定形式的四次方程ax^4+bx^3+cx^2+dx+e ,确定根的总和与根的乘积之间的绝对差。请注意,根不必是真实的,它们也可以是复杂的。

例子:

Input: 4x^4 + 3x^3 + 2x^2 + x - 1
Output: 0.5

Input: x^4 + 4x^3 + 6x^2 + 4x + 1
Output: 5

方法:求解四次方程以获得每个单独的根将是耗时且低效的,并且将需要大量的精力和计算能力。一种更有效的解决方案利用以下公式:

四次ax^4+bx^3+cx^2+dx+e总是有根源\dfrac{-b}{a}以及根的乘积\dfrac{e}{a}

因此,通过计算|\dfrac{-b}{a}- \dfrac{e}{a}|我们发现根的总和与乘积之间的绝对差。

下面是上述方法的实现:

C++
// C++ implementation of above approach 
#include  
using namespace std; 
  
// Function taking coefficient of 
// each term of equation as input 
double sumProductDifference(int a, int b, 
                            int c, int d,
                            int e) 
{ 
    // Finding sum of roots 
    double rootSum = (double)(-1 * b) / a; 
  
    // Finding product of roots 
    double rootProduct = (double) e / a; 
      
    // Absolute difference 
    return abs(rootSum - rootProduct); 
} 
  
// Driver code 
int main() 
{ 
    cout << sumProductDifference(8, 4, 6, 4, 1);
      
    return 0; 
} 
  
// This code is contributed 
// by ANKITRAI1


Java
// Java implementation of above approach 
  
public class GFG {
    // Function taking coefficient of
    // each term of equation as input
    static double sumProductDifference(int a, int b, int c, int d, int e) {
        // Finding sum of roots
        double rootSum = (double)(-1 * b) / a;
  
        // Finding product of roots
        double rootProduct = (double) e / a;
          
        // Absolute difference
        return Math.abs(rootSum - rootProduct);
    }
  
    // Driver Code
    public static void main(String args[]) {
        System.out.println(sumProductDifference(8, 4, 6, 4, 1));
    }
}


Python3
# Python implementation of above approach
  
# Function taking coefficient of 
# each term of equation as input
def sumProductDifference(a, b, c, d, e):
  
    # Finding sum of roots
    rootSum = (-1 * b)/a 
  
    # Finding product of roots
    rootProduct = e / a 
  
    # Absolute difference
    return abs(rootSum-rootProduct) 
  
print(sumProductDifference(8, 4, 6, 4, 1))


C#
// C# implementation of above approach 
using System;
  
class GFG
{
// Function taking coefficient of
// each term of equation as input
static double sumProductDifference(int a, int b,
                                   int c, int d, 
                                   int e) 
{
    // Finding sum of roots
    double rootSum = (double)(-1 * b) / a;
  
    // Finding product of roots
    double rootProduct = (double) e / a;
      
    // Absolute difference
    return Math.Abs(rootSum - rootProduct);
}
  
// Driver Code
public static void Main() 
{
    Console.Write(sumProductDifference(8, 4, 6, 4, 1));
}
}
  
// This code is contributed 
// by ChitraNayal


PHP


输出:
0.625

说明:输入方程为8x^4+4x^3+6x^2+4x+1

通过寻找|\dfrac{-b}{a}-\dfrac{e}{a}| ,我们得到|\dfrac{-4}{8} - \dfrac{1}{8}|

这是\dfrac{5}{8} , 或者0.625