英文:
Formating the tittle of a graph that has varabiles and latex
问题
使用以下代码中的用户输入来更改图表标题,我想让它以最简单的形式显示图表标题,例如当a=1,b=0,c=-1时,我希望它显示为 "x-1",但实际上显示的是 "1x+0x+-1"。
英文:
i was trying to make a graph tittle change depending on the users input using the following piece of code plt.title(f"{a}$x^2+{b}x+{c}$")
i would like it to display the title of the graph in the most simple form for example when a=1 b=0 c=-1
i want it to display x-1 as the title
but instead it is displaying 1x+0x+-1 as the tittle
答案1
得分: 1
a = 1
b = 0
c = -1
def format_title(a, b, c):
title = ''
if a == 1:
title += 'x^2'
else:
title += f'{a}x^2'
if b != 0:
if b > 0:
title += '+'
title += f'{b}x'
if c != 0:
if c > 0:
title += '+'
title += f'{c}'
return title
print(format_title(a, b, c))
Output:
x^2-1
英文:
Simple python code:
a = 1
b = 0
c = -1
def format_title(a, b, c):
title = ''
if a == 1:
title += 'x^2'
else:
title += f'{a}x^2'
if b != 0:
if b > 0:
title += '+'
title += f'{b}x'
if c != 0:
if c > 0:
title += '+'
title += f'{c}'
return title
print(format_title(a, b, c))
Output:
x^2-1
答案2
得分: 0
以下是代码的翻译部分:
def ft(*coefs, exponent="x", cdp=0):
title = ""
cstring = f"{{:.{cdp}f}}" # 用于格式化系数的小数位数
nc = len(coefs) - 1
for i in range(nc, -1, -1):
if coefs[nc - i] != 0:
# 获取符号
sign = "+" if coefs[nc - i] > 0 and i < nc else ("-" if i == nc and coefs[nc - i] == -1 else "")
# 获取系数
c = cstring.format(coefs[nc - i]) if abs(coefs[nc - i]) != 1 or i < nc else ""
# 获取指数
exp = f"{exponent}^{i}" if i > 1 else (exponent if i == 1 else "")
part = f"{sign}{c}{exp}"
title += f"{part}"
return f"${title}$"
这段代码是一个通用的函数,它可以接受任意数量的系数(不仅限于二次方程),并可以将系数输出为指定小数位数(默认为不带小数位,即整数)。对于你的例子,你可以使用:
print(ft(1, 0, -1))
$x^2-1$
但你也可以使用以下方式:
print(ft(-4.765, 0, 2.383, -0.351, cdp=2))
$-4.76x^3+2.38x-0.35$
英文:
A more complicated, but generalisable option would be:
def ft(*coefs, exponent="x", cdp=0):
title = ""
cstring = f"{{:.{cdp}f}}" # number of decimal places to format the coefficents
nc = len(coefs) - 1
for i in range(nc, -1, -1):
if coefs[nc - i] != 0:
# get the sign
sign = "+" if coefs[nc - i] > 0 and i < nc else ("-" if i == nc and coefs[nc - i] == -1 else "")
# get the coefficient
c = cstring.format(coefs[nc - i]) if abs(coefs[nc - i]) != 1 or i < nc else ""
# get the exponent
exp = f"{exponent}^{i}" if i > 1 else (exponent if i == 1 else "")
part = f"{sign}{c}{exp}"
title += f"{part}"
return f"${title}$"
This can take in any number of coefficients (so not just quadratics) and also output the coefficients with to any number of decimals places (it defaults to just output with no decimal places, i.e., as integers). For you case you still have:
print(ft(1, 0, -1))
$x^2-1$
but you could also do, e.g.,
print(ft(-4.765, 0, 2.383, -0.351, cdp=2))
$-4.76x^3+2.38x-0.35$
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论