sharpie7 / circuitjs1

Electronic Circuit Simulator in the Browser
GNU General Public License v2.0
2.29k stars 633 forks source link

Feature: add boolean operators to VCVS expressions #579

Closed ormaaj closed 3 years ago

ormaaj commented 3 years ago

It is useful have compossible operators whose result can be used directly as either an output or function argument. Expressions don't always evaluate to something at the moment, or possibly evaluate to a null value. (Don't know with parsing / evaluation errors not yet implemented, this could be a missing feature or bug).

It may be necessary to use bools or ints as intermediary results, using some reflection during evaluation - eventually converting the result to double. Given a skim through the code I notice there's a type field in the Expr class already which could be an attempt to support this, or perhaps it's just for storing the type temporarily in order to make boolean operators compossible exclusively with themselves.

ltwiki says: "For Boolean operations True is 1 and False is 0. Boolean conversions return True if evaluates to greater than .5, else False." ...So the spices don't agree on this? At least I don't think ngspice does that for brace or B-source expressions.

pfalstad commented 3 years ago

I don't follow this. Could you give an example of what you are asking for?

ormaaj commented 3 years ago

Basically the boolean operators should behave as in C so that for a VCVS an expression like (a + 3) > 5 literally outputs 1V if a > 2.

I guess you can sort of abuse select to do that at the moment. The upper circuit should behave like the lower: example

pfalstad commented 3 years ago

That's not abuse, that's what select is for.

It should be reporting a parse error somehow if you use unsupported operators. I guess we could add comparison operators too, evaluating to 1 for true and 0 for false. Is that what LTspice does?

ormaaj commented 3 years ago

That's not abuse, that's what select is for.

It should be reporting a parse error somehow if you use unsupported operators. I guess we could add comparison operators too, evaluating to 1 for true and 0 for false. Is that what LTspice does?

Pretty much. I just recently started with ltspice, but it's actually surprisingly interoperable. Of course this boolean stuff opens up some gotchas with float equality, but provided one knows about that it's hugely useful.

A ternary operator and/or function is also really useful. I thought it was already there but guess not.

References: