Solving the cubic equation of one element (half-lookup)

Source: Internet
Author: User
Description is a one-dimensional cubic equation, such as ax3 + bx2 + cx + D = 0. The coefficients (A, B, C, and D are all real numbers) of the equation are given, and it is agreed that the equation has three different solid roots (the root range is between-100 and 100 ), and the absolute value of the root and root difference> = 1. Please find three solid roots of this equation.

There is only one input row, which contains four real numbers a, B, c, d, separated by one or more spaces.
There is only one row in output, including three integers. The reason is that three solid roots are arranged in ascending order (spaces are left between the root and the root), and the result is accurate to the second decimal point.

Sample input1-5-4 20

Sample output-2.00 2.00 5.00
Solution:
If f (a) * F (B) <0, there is at least one root in the (a, B) interval. The scope of the root is between-100 and 100, and the absolute value of the root and root difference is greater than or equal to 1. Therefore, you only need to [-100,-99), [-99, -98 )... [99,100), traverse all the intervals, and then use half to find the root.
AC code:
# Include <stdio. h> double A, B, C, D; double func (Double X) {double result; result = A * x + B * x + C * x + D; // calculate the value of f (x) return result;} int main () {Double X; scanf ("% lf", & A, & B, & C, & D); For (INT I =-100; I <= 100; I ++) {If (func (I * 1.0) * func (I + 1) * 1.0) <0) // determine whether the root {double low = I * 1.0, high = (I + 1) * 1.0, mid; while (high-low> 1e-8) in the interval) {mid = (high + low)/2; If (func (MID) * func (high) <= 0) // perform semi-query low = mid; else high = mid;} printf ("%. 2lf ", mid);} If (func (I * 1.0) = 0) // another case is that the root is printf (" %. 2lf ", I * 1.0);} return 0 ;}



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.