自动计算二次方程

自动计算二次方程

我已经更新了我最近的帖子,我正在尝试使其自动化,但需要方法上的帮助,我已经阅读了所有我能读到的宏书,但找不到答案。

\documentclass{article}
\usepackage{mathtools}

\begin{document}

\begin{gather*}
ax^2+bx+c=0,\\
\shortintertext{for example: }
x^2 + 2x -15 = 0 \\ %this what I want to automate
(x+5)(x-3) = 0, \\  %to give this answer
\shortintertext{therefore}
 c=5 \times -3 = -15\quad \text{and}\quad b = 5-3=2. %and this so I can insert the results into another diagram I have made.  
\end{gather*}

\end{document} 

任何帮助或指导都将非常有用。

答案1

这是一个xfp适用于任何引擎的解决方案——它也不是完美的,你需要做很多事情ifthenelse来美化输出,但是......

\documentclass{article}
\usepackage{mathtools}
\usepackage{xfp}
\usepackage{ifthen}

\newcommand{\secondorder}[3]{% a, b ,c
    \def\discr{\fpeval{#2*#2-4*#1*#3}}
    \ifthenelse{\discr > 0}{
        \def\xone{\fpeval{(-#2+sqrt{\discr})/#1/2}}
        \def\xtwo{\fpeval{(-#2-sqrt{\discr})/#1/2}}
        \begin{gather*}
            ax^2+bx+c=0,\\
            \shortintertext{for example: }
            #1\cdot x^2 + (#2)\cdot x + (#3) = 0 \\
            (x-(\xone))(x-(\xtwo)) = 0, \\
            \shortintertext{therefore}
            c=\xone \times (\xtwo) = #3 \quad \text{and}\quad b = -(\xone)-(\xtwo)=#2.
        \end{gather*}%
        }{%
        \begin{gather*}
            ax^2+bx+c=0,\\
            \shortintertext{for example: }
            #1\cdot x^2 + (#2)\cdot x + (#3) = 0 \\
            \shortintertext{has no real roots}
        \end{gather*}
    }
}

\begin{document}

\secondorder{1}{2}{-15}

\secondorder{1}{2}{1}

\secondorder{1}{0}{-1}

\end{document}

在此处输入图片描述

答案2

这是使用 Lua 的解决方案。它并不完美,我假设主系数为 1,并且我对四舍五入浮点值不太小心,但它应该很容易根据您的需要进行调整。

\documentclass{article}
\usepackage{luacode}

\begin{luacode}
-- Computes the roots of x^2+bx+c=0
-- Returns nothing if they aren't real
function roots(b, c)
    local delta = b*b-4*c
    if delta > 0 then
        deltasq = math.sqrt(delta)
        local r1 = math.round((-b-deltasq)/2)
        local r2 = math.round((-b+deltasq)/2)
        return r1, r2
    end
end

-- Outputs x^2+bx+c in developed form to LaTeX
function display_polynome(b, c)
    p = "x^2"
    if b > 0 then
        p = p .. "+" .. tostring(b) .. "x"
    elseif b < 0 then
        p = p .. tostring(b) .. "x"
    end
    if c > 0 then
        p = p .. "+" .. tostring(c)
    elseif c < 0 then
        p = p .. tostring(c)
    end
    tex.print(p)
end

-- Outputs x^2+bx+c in factorized form to LaTeX
function display_factorized_polynom(b, c) 
    r1, r2 = roots(b, c)
    p = "(x"
    if r1 > 0 then
        p = p .. "-" .. tostring(r1) .. ")(x"
    elseif r1 < 0 then
        p = p .. "+" .. tostring(-r1) .. ")(x"
    end
    if r2 > 0 then
        p = p .. "-" .. tostring(r2) .. ")"
    elseif r2 < 0 then
        p = p .. "+" .. tostring(-r2) .. ")"
    end
    tex.print(p)
end
\end{luacode}

\begin{document}

$\directlua{display_polynome(2, -15)}$

$\directlua{display_factorized_polynom(2, -15)}$

\end{document}

结果

如果您使用 VS Code,则可以获得加分,因为它会在luacode环境中切换到 Lua 语法高亮。

相关内容