开发者

Java - drawing Polynomials

开发者 https://www.devze.com 2023-02-25 00:00 出处:网络
I\'m just wondering how can I draw a polynomial lik开发者_如何学Pythone that X^2+2*X^4+... in efficient way and make it look like a real one. I mean powers is up-script and so.If you have an environm

I'm just wondering how can I draw a polynomial lik开发者_如何学Pythone that X^2+2*X^4+... in efficient way and make it look like a real one. I mean powers is up-script and so.


If you have an environment with a good Unicode font, you could relatively easily create your own polynomial toString(). Unicode has all Arabic numerals defined as superscript, most of them in the Superscripts and Subscripts block:

x⁰: U+2070 
x¹: U+00B9  // Not in U207x range!
x²: U+00B2  // Not in U207x range!
x³: U+00B3  // Not in U207x range!
x⁴: U+2074
x⁵: U+2075
x⁶: U+2076
x⁷: U+2077
x⁸: U+2078
x⁹: U+2079
x⁻: U+207B

Thus, constructing x⁻⁴² (x^-42) would be possible by printing U+0078 U+207B U+2074 U+00B2.

Notice that the font you use to print this must have these characters defined.


The Unicode approach has considerable appeal, but it requires font support. As an alternative, consider How to Use HTML in Swing Components, e.g.

new JLabel("<html><i>x</i><sup>2</sup> + <i>x</i><sup>4</sup></html>")

Java - drawing Polynomials


Ok, to help you get started, here's what you need to do on a high level:

  • Extend a JPanel. This new class (lets say PolynominalPanel extends JPanel) will draw your polynominal.
  • Override the paintComponent(Graphics g) method
  • Use the "Graphics" argument to set the linestroke of your choice (cast to Graphics2D and use setStroke()).
  • Define a new class that transforms X and Y values to values in your JPanel coordinates. This allows you to translate, mirror, rotate ... etc.. all your points in a uniform way. (So for each X and Y in your polynominal, transform this with a formula of your choosing, so that the polynominal is drawn in the bounds of the JPanel).The point here is that you want to map a part of your polynominal to the bounds of your PolynominalPanel. This is the part of the polynominal you are interested in. This depends on the polynominal.
  • Sample your polynominal in a discrete way. For instance, you could sample it for each X pixel, or possibly you could sample it at a lower rate for better performance. (Though per pixel should be fine)
  • Use the Graphics.drawLine() method to draw lines. You should use the transformed values that you have sampled before.

And voila, you're done!

Hope this helps!


What do you mean: drawing the formula or drawing the graph. It seems you want the former. You could have a look at LaTex.

0

精彩评论

暂无评论...
验证码 换一张
取 消