Find roots of a function using JavaView
Code: "javaview_roots_function.py". Programming language: Python DMelt Version 2.5. Last modified: 07/02/1974. License: Pro
https://datamelt.org/code/cache/javaview_roots_function_2949.py
To run this script using the DMelt IDE, copy the above URL link to the menu [File]→[Read script from URL] of the DMelt IDE.


# find roots of real-valued functions of one variable.
# Type a new function and study its zero crossings.
# @author   Konrad Polthier, Sergei Chekanov 

from jv.geom import PgPointSet,PgPolygon
from jv.number import PuDouble,PuInteger
from jv.project import PvCameraIf,PvDisplayIf 
from jv.function import PuFunction
from jhplot import HJavaView
from java.awt import Color

# find root of this function
# Use any combination: abs,acos,asin,atan,acot,exp,log,round,sin,cos,cot,tanh, etc.

FUN="u*cos(u+1.)-sin(u)"


# graph representin function in 2D
m_graph = PgPolygon(2);
m_graph.setName("Graph of Function");

# graph with roots
m_root  = PgPointSet(2);
m_root.setName("Roots of function");
m_discr =  PuInteger("Discr of Polygon");

# actual function
m_fx  = PuFunction(1, 1);
m_fx.setName("Function");
m_fx.setExpression(FUN);


# X min and Xmax
m_xMin            = PuDouble("xMin");
m_xMin.setDefBounds(-20., 20., 0.1, 1.0);
m_xMin.setDefValue(-10.);
m_xMin.init();

m_xMax            = PuDouble("xMax");
m_xMax.setDefBounds(-20., 20., 0.1, 1.0);
m_xMax.setDefValue( 10.);
m_xMax.init();

#Number of equidistant samples being computed in the definition interval.
#The function will be evaluated at sample points to find starting
#values for the searching algorithm
m_discr.setDefBounds(2, 200, 1, 5);
m_discr.setDefValue(200);
m_discr.init();

m_graph.setNumVertices(m_discr.getValue());
m_root.showIndices(True);
m_root.setGlobalVertexColor(Color.blue);
m_root.setGlobalVertexSize(4.);

nov = m_graph.getNumVertices();
x   = m_xMin.getValue();
dx  = (m_xMax.getValue()-x)/(nov-1.);
for i in range(nov):
       y = m_fx.eval(x);
       m_graph.setVertex(i, x, y);
       x = x+ dx;

# find ROOT
# Compute roots of function in a specified interval
# Method just invokes a numerical algorithm, and assigns roots to pointset of roots
from jvx.numeric import PnRootFinder
maxNumRoots = m_discr.getValue();
root = PnRootFinder.findRoots(m_fx, m_xMin.getValue(), m_xMax.getValue(), maxNumRoots);
numRoots = root.getSize();
m_root.setNumVertices(numRoots);
for i in range(numRoots):
        m_root.setVertex(i, root.getEntry(i), 0.);


c1= HJavaView()
c1.draw(m_graph)
c1.draw(m_root)
view=c1.getView()
disp=view.getDisplay()

disp.selectCamera(PvCameraIf.CAMERA_ORTHO_XY);    # project onto xy-plane
disp.setMajorMode(PvDisplayIf.MODE_INITIAL_PICK); # force picking of initial point

c1.visible()

You see the box below because you did not login.